目录
什么是钩子(hook)?
钩子到生命周期的映射
vue的生命周期钩子示例
onRenderTracked/onRenderTriggered
用钩子还是watch?
beforeCreate -> 使用 setup()
created -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeUnmount -> onBeforeUnmount
unmounted -> onUnmounted
errorCaptured -> onErrorCaptured
renderTracked -> onRenderTracked
renderTriggered -> onRenderTriggered
activated -> onActivated
deactivated -> onDeactivated
import {
ref,
defineComponent,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
onErrorCaptured,
} from 'vue'
export const LifeExample01 = defineComponent({
setup() {
const toggle = ref(true)
onBeforeUpdate(() => console.log('before update'))
onUpdated(() => console.log('updated'))
onErrorCaptured((error) => { // 捕获异常
console.error('报错走的方法', error)
// toggle.value = false
})
return () => {
return (
)
}
}
})
const A = defineComponent({
setup() {
onBeforeMount(() => { console.log('before mount') })
onMounted(() => { console.log('mounted') })
onBeforeUnmount(() => { console.log('before unmount') })
onUnmounted(() => { console.log('unmounted') })
// throw "333"; // 报错
return () => A组件
}
})
import {
ref,
defineComponent,
onRenderTracked,
onRenderTriggered
} from 'vue'
export const LifeExample02 = defineComponent({
setup() {
const c = ref(0)
onRenderTriggered((x) => {
console.log('trigger', x) // 多次触发set
})
onRenderTracked((x) => {
console.log('track', x) // get 1次
})
return () => {
return c.value++}>{c.value}
}
}
})
onActivated/onDeactivated
import {
ref,
defineComponent,
onUnmounted,
onActivated,
onDeactivated,
KeepAlive
} from 'vue'
export const LifeExample03 = defineComponent({
setup() {
const toggle = ref(true)
return () => {
return (
{toggle.value && }
)
}
}
})
const B = defineComponent({
setup() {
onUnmounted(() => {
// KeepAlive内的复杂组件会缓存,不走销毁钩子
console.log('unmounted')
})
onActivated(() => {
console.log('active显示')
})
onDeactivated(() => {
console.log('deactive隐藏')
})
return () => B组件
}
})