# 常用的 Api
# watchEffect
概述: 立即执行传入的一个函数,并响应式追踪其依赖,并在其依赖变更时重新运行该函数。
停止侦听: 清除副作用。如果有时候
watchEffect执行的是一个异步函数。可能在运行完stop()之后并异步任务未完全清除、或者异步任务短时间内多次触发防止重复操作。 使用watchEffect的第一个参数onInvalidate作为入参,传入一个回调函数。配置选项。
flush:sync(组件更新同步触发)pre(组件更新之前触发)post(默认为post)。
onTrack: 当Reactive与Ref对象被作为依赖追中会触发。onTrigger: 当依赖数据更新触发。
import { watchEffect, ref } from 'vue'
const count = ref(0)
const stop = watchEffect(() => console.log(count.value))
count.value++ // 改变会触发watchEffect, 输出1
stop() /* 类似2.x的$watch的返回值 */
// 副作用函数
watchEffect(onInvalidate => {
const resp = await axios(props.id)
onInvalidate(() => {
// 此函数会在 id改变时或者侦听时取消之前的异步操作
// doSomething.. cancelToken()
})
})
// 配置对象
watchEffect(
() => { /* ... */ },
{
flush: 'sync',
onTrack (e) {
// ...
},
onTrigger (e) {
// ...
}
}
)
# watch
- 概述: 与2.x中
$watch相同。但是在第三个参数中也添加了onInvalidate函数,用来清除异步或者其他。
# useAttrs
import { useAttrs } from 'vue'
const $attrs = useAttrs() as unkown as any
V3优化
Vue3中$listeners已经合并到了$attrs中
# defineProps
- 概述:定义父组件传的值
import { defineProps } from 'vue'
const props = defineProps<{
userId: string
}>()
# defineEmits
- 概述:定义可触发的父组件的自定义事件
import { defineEmits } from 'vue'
const emits = defineEmits<{
(e: 'event-name', value: any): void
}>()
# defineExpose
- 概述:外部组件通过Ref获取组件实例时,可获得的属性或者方法
import { defineExpose } from 'vue'
defineExpose({
// ...
})
# 3.3增加的 defineOptions
便捷更新
使用 <script setup> 定义组件名称或者其他Options需要重新写一个 <script> 块 所以推出了defineOptions
import { defineOptions } from 'vue'
defineOptions({
name: 'MyComponent',
inheritAttrs: false
})
# getCurrentInstance
- 概述:获取当前组件实例
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()!
# nextTick
import { nextTick } from 'vue'
nextTick(() => { /* do... */ })
# defineAsyncComponent
- 概述:在setup中定义异步组件
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() => import('./filepath'))