多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] >[success] # 生命周期函数的新写法 **vue2.x** 版本中 **[生命周期写法](https://www.kancloud.cn/wangjiachong/vue_notes/2140861)**,目前新的 **composition API** 中的 **生命周期** 都需要写在 **setup函数** 中,用 **按需引入** 的方式来使用,具体代码如下: **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>生命周期函数的新写法</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ setup(){ const { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } = Vue const name = ref('dell') // beforeMount 等同于 onBeforeMount onBeforeMount(() => { console.log('onBeforeMount') }) // mounted 等同于 onMounted onMounted(() => { console.log('onMounted') }) // beforeUpdate 等同于 onBeforeUpdate onBeforeUpdate(() => { console.log('onBeforeUpdate') }) // updated 等同于 onUpdated onUpdated(() => { console.log('onUpdated') }) // beforeUnmount 等同于 onBeforeUnmount(当组件从页面v-if隐藏移除时会执行) onBeforeUnmount(() => { console.log('onBeforeUnmount') }) // unmounted 等同于 onUnmounted(组件从页面移除后执行) onUnmounted(() => { console.log('onUnmounted') }) // 定义方法 const handleClick = () => { name.value = 'lee' } return { name, handleClick } }, template: ` <div @click="handleClick">{{name}}</div> ` }) const vm = app.mount('#root') </script> </html> ~~~ **composition API** 中很多的 **生命周期** 与原来一样,不同的就是 **名字有所改变而已**。 >[success] ## 弃用的生命周期 在 **composition API 中有 beforeCreate 与 created 这 2 个生命周期函数我们是不能使用的** ,因为 **setup 函数执行的时间点,在 beforeCreate 与 created 之间** ,所以这 **2** 个 **生命周期** 中要写的东西,直接写在 **setup** 中就可以了。 >[success] ## 新的的生命周期 **composition API** 出了 **2** 个新的 **生命周期函数** ,**onRenderTracked 与 onRenderTriggered** ,代码如下: **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>生命周期函数的新写法</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> const app = Vue.createApp({ setup(){ const { ref, onRenderTracked, onRenderTriggered } = Vue const name = ref('小明') // 每次渲染后重新收集响应式依赖 onRenderTracked(() => { console.log('onRenderTracked') }) // 每次触发页面重新渲染时自动执行 onRenderTriggered(() => { console.log('onRenderTriggered') }) // 定义方法 const handleClick = () => { name.value = 'lee' } return { name, handleClick } }, template: ` <div @click="handleClick">{{name}}</div> ` }) const vm = app.mount('#root') </script> </html> ~~~