vue3常用知识点小结

243 阅读1分钟

Vue3学习笔记01

主要涉及script-setup的用法,会混合ts的相关使用

1. 应用API

  1. 去掉全局挂载,当然也可以用(app.config.globalProperties.$http
  2. app.component : 注册组件,返回app实例 | 只传个name,返回组件
  3. app.directive : 注册指令,返回app历史 | 只传个name,返回指令
  4. app.provide : 配合inject使用。(与组件中的provide有区别)
  5. app.use : 安装插件,插件对象需要暴露install方法,第一个参数放app
  6. app.mount : 挂载

2. 部分API使用

  1. import { createApp } from 'vue' : 创建应用实例app
  2. import { nextTick } from 'vue' : 原this.$nextTick
  3. import { useCssModule } from 'vue' : 在setup中调用const style = useCssModule()可以访问CSS模块,配合<style module>使用
  4. import { useSlots, useAttrs } from 'vue': 获取slots 和 attrs

3.内置组件

  1. <component>: 配合is使用
<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>

<template>
  <component :is="Foo" />
  <component :is="someCondition ? Foo : Bar" />
</template>
  1. <transition>
  2. <transition-group>
  3. <keep-alive>
  4. <slot>
  5. <teleport>

4. 响应式API

  1. reactive : 响应式
  2. readonly : 不可修改
  3. shallowReactive : 浅reactive
  4. shallowReadonly : 浅readonly
  5. isProxy : 是否为reactive、readonly
  6. isReactive : 是否为reactive
  7. isReadonly : 是否为readonly
  8. toRaw : 返回代理的原始对象
  9. markRaw : 标记对象使其不会转为proxy
  10. ref : 使用.value
  11. unref : 返回内部值
  12. toRef :
  13. toRefs : 类似解构获取值
  14. isRef :
  15. computed: 会缓存
    const plusOne = computed(() => {
        count.value + 1
    })
    const plusTwo = computed({ // 有get,set的
        get: () => count.value + 1,
        set: val => {
            count.value = val - 1
        }
    })
  1. watch :
// 监听单一源,通常用法
watch(() => state.count, (newVal, oldVal) => {
    /* ... */
})
// 监听多个源
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  /* ... */
})
// 深度监听,立即执行
watch(() => state.count, (newVal, oldVal) => {
    /* ... */
}, { deep: true, immediate: true })
// 直接监听ref,停止监听
const stopWatch = watch(count, (newVal, oldVal) => {/* ... */})
stopWatch()
  1. watchEffect: 理解是收集回调的依赖,有更新统统执行一遍
watchEffect(() => {
    /* ...涉及到响应式数据 */
    console.log(count.value)
})

5. 组合式API相关

  1. setup(props, {attrs, slots, emit, expose}): 普通用法setup的参数,其中props使用toRefs(props)获取props会方便点。需要return。return可以是一个返回h渲染函数的方法
  2. provide/injectInjectionKey
import { InjectionKey, provide, inject } from 'vue'
export const key: InjectionKey<string> = Symbol()

// 父组件
provide(key, 'foo') // 若提供非字符串值将出错
// 子组件
const foo = inject(key) // foo 的类型: string | undefined
  1. definePropswithDefaults: 设置默认值
const props = defineProps({
  foo: String
})
// ts带类型的用法
const props = defineProps<{
    foo: string
    bar?: number
}>()
interface Props {
    foo?: string
    bar: number
    labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
    bar = 2,
    labels: () => ['one', 'tow']
})
props: {
    count: {
        type: Number,
        default: 0,
        validator: value => value >= 0
    }
} // 帮助记忆
  1. defineEmits
const emit = defineEmits(['change', 'delete'])
const emit = defineEmits<{
    (e: 'change', id: number): void
    (e: 'delete', name: string): void
}>()
emits:{
    click: null, // 无验证
    submit: payload => {
        return payload.username && payload.password
    }
}
  1. defineExpose: script-setup默认不会暴露组件里的数据
  2. useSlots: 获取$slots
  3. useAttrs: 获取$attrs
  4. 直接使用await

6. 组件样式特性

  1. <style scoped>
  2. scoped中深度选择器: :deep(div) { /*...*/ }
<style scoped>
.a :deep(.b) {
    color: red;
}
</style>
  1. 插槽选择器: :slotted(div) { /*...*/ }
  2. 全局选择器: :global(.red) { /*...*/ }
  3. <style module>useCssModule
<template>
  <p :class="$style.red">
    This should be red
  </p>
</template>

<style module>
.red {
  color: red;
}
</style>
// 自定义注入module名称
<template>
  <p :class="classes.red">red</p>
</template>

<style module="classes">
.red {
  color: red;
}
</style>
// 与组合式API使用,需配合 useCssModule() 使用

// 默认, 返回 <style module> 中的类
useCssModule()
// 命名, 返回 <style module="classes"> 中的类
useCssModule('classes')
  1. 动态CSS:
.text {
    color: v-bind('theme.color');
}

7. 部分生命周期

  1. onBeforeMount
  2. onMounted
  3. onBeforeUnmount
  4. onUnmounted
  5. onActivated

8. 其他知识点

  1. src引入,script-setup没有这个
<template src="./template.html"></template>
<style src="./style.css"></style>
<script src="./script.js"></script>
  1. 使用vite创建项目: npm init vite@latest
  2. 命名空间组件
<script setup>
import * as Form from './form-components'
</script>

<template>
  <Form.Input>
    <Form.Label>label</Form.Label>
  </Form.Input>
</template>
  1. 组件中根元素不再只能有一个



慢慢添加知识点,慢慢简化




9. 指令、attribute、等等

  1. <slot name="header" v-bind="{row}" />
  2. v-slot -> # : v-slot:header="{row}" -> #header="{row}"
  3. v-memo
  4. ref
  5. is
  6. v-model
  7. inheritAttrs: false