在 scirpt引入:
import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured, ref, reactive } from 'vue'
在 setup 调用:
export default defineComponent ({ setup() { onBeforeMount(() => {
}); onMounted(() => {
}); onBeforeUpdate(() => {
}); onUpdated(() => {
}); onBeforeUnmount(() => {
}); onUnmounted(() => {
}); onErrorCaptured(() => {
}); return { } }, })
1、页面加载前 --- beforeMount:挂在开始之前被调用,相关的render函数首次被调用(虚拟DOM),实例已完成以下的配置: 编译模板,把data里面的数据和模板生成html,完成了el和data 初始化,注意此时还没有挂在html到页面上。
onBeforeMount() { console.log("App ===> 相当于 vue2.x 中 beforeMount") },
2、挂载事件等 --- mounted:挂载完成,也就是模板中的HTML渲染到HTML页面中,此时一般可以做一些ajax操作,mounted只会执行一次。
onMounted() { console.log("App ===> 相当于 vue2.x 中 mounted") },
3、数据更新前 --- beforeUpdate:在数据更新之前被调用,发生在虚拟DOM重新渲染和打补丁之前,可以在该钩子中进一步地更改状态,不会触发附加地重渲染过程。
onBeforeUpdate() { console.log("App ===> 相当于 vue2.x 中 beforeUpdate") },
4、数据更新时候 --- updated:在由于数据更改导致地虚拟DOM重新渲染和打补丁只会调用,调用时,组件DOM已经更新,所以可以执行依赖于DOM的操作,然后在大多是情况下,应该避免在此期间更改状态,因为这可能会导致更新无限循环,该钩子在服务器端渲染期间不被调用。
onUpdated() { console.log("App ===> 相当于 vue2.x 中 updated") },
5、页面销毁前 --- beforeDestroy:在实例销毁之前调用,实例仍然完全可用,
- 这一步还可以用this来获取实例,
- 一般在这一步做一些重置的操作,比如清除掉组件中的定时器 和 监听的dom事件。
onBeforeUnmount() { console.log("App ===> 相当于 vue2.x 中 beforeDestroy") },
6、页面销毁后 --- destroyed:在实例销毁之后调用,调用后,所以的事件监听器会被移出,所有的子实例也会被销毁,该钩子在服务器端渲染期间不被调用。
onUnmounted() { console.log("App ===> 相当于 vue2.x 中 destroyed") },
7、错误处理机制 --- errorCaptured:指定组件的渲染和观察期间未捕获错误的处理函数。这个处理函数被调用时,可获取错误信息和 Vue 实例。
onErrorCaptured() { console.log("Counter ===> 相当于 vue2.x 中 errorCaptured") }
Vue2.0 API | Vue3.0 API (钩在里面 setup) |
---|---|
beforeCreate |
不需要* |
created |
不需要* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |
注:Vue3.0 的 setup,
是围绕 beforeCreate
和 created
生命周期挂钩运行的,因此无需显式定义;也就是说,在这些挂钩中编写的任何代码,都应直接在setup
函数中编写。
© 著作权归作者所有
发表评论