14:vue3 生命周期(生命周期钩子)

每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤,比如设置好数据侦听,编译模板,挂载实例到 DOM,以及在数据改变时更新 DOM。在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。

生命周期函数

       创建期:beforeCreate     created

       挂载期:beforeMount      mounted

       更新期:beforeUpdate     updated

       销毁期:beforeUnmount  unmounted

下面是实例生命周期的图表。你现在并不需要完全理解图中的所有内容,但以后它将是一个有用的参考。

 

 

示例代码,App.vue中书写

 1 <template>
 2   <p>{{ message }}</p>
 3   <button @click="updateHander">更新按钮</button>
 4 </template>
 5 
 6 <script>
 7 
 8 export default{
 9     data(){
10       return{
11         message:"组件更新前数据"
12       }  
13     },
14     methods:{
15       updateHander(){
16         this.message="组件更新后数据"
17       }
18     },
19     beforeCreate() {
20       console.log("组件创建之前");
21     },
22     created() {
23       console.log("组件创建之后");
24     },
25     beforeMount() {
26       console.log("组件挂载之前");
27     },
28     mounted() {
29       console.log("组件挂载之后");
30     },
31     beforeUpdate() {
32       console.log("组件更新之前");
33     },
34     updated() {
35       console.log("组件更新之后");
36     },
37     beforeUnmount() {
38       console.log("组件销毁之前");
39     },
40     unmounted() {
41       console.log("组件销毁之后");
42     }
43     
44 }
45 </script>

 

posted on 2023-07-07 14:52  wuzx-blog  阅读(51)  评论(0编辑  收藏  举报