Vue 进阶之路(十四)

之前的文章我们对 vue 的基础用法已经有了很直观的认识,本章我们来看一下 vue 中的生命周期函数。

上图为 Vue官方为我们提供的完整的生命周期函数的流程图,下面的案例我们只是走了部分情况流程,但所有的生命周期函数都涉及到了。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>vue</title>
 6     <script src="https://cdn.jsdelivr.net/npm/vue"></script>
 7 </head>
 8 <body>
 9 <div id="app">
10     <child v-if="show"></child>
11     <button @click="handleClick">{{title}}</button>
12 </div>
13 <script>
14     Vue.component("child", {
15         beforeDestroy() {
16             console.log("beforeDestroy", this.$el);
17         },
18         destroyed() {
19             console.log("destroyed", this.$el);
20         },
21         template: `<p>我是 child 子组件</p>`,
22     });
23     var app = new Vue({
24         el: '#app',
25         data: {
26             title: "hello world",
27             show: true
28         },
29         beforeCreate() {
30             console.log("beforeCreate", this.$el);
31         },
32         created() {
33             console.log("created", this.$el);
34         },
35         beforeMount() {
36             console.log("beforeMounted", this.$el);
37         },
38         mounted() {
39             console.log("mounted", this.$el);
40         },
41         beforeUpdate() {
42             console.log("beforeUpdate", this.$el);
43         },
44         updated() {
45             console.log("updated", this.$el);
46         },
47         methods: {
48             handleClick() {
49                 this.show = !this.show;
50             }
51         }
52     })
53 </script>
54 </body>
55 </html>

从上面的代码中我们可以看出 vue 的生命周期函数有:

beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed

这几个生命周期函数的意思分别是:

  beforeCreate:组件创建前,

  created:组件创建完成,

  beforeMount:组件挂载前,

  mounted:组件挂载完成,

  beforeUpdate:组件更新前,

  updated:组件更新完成,

  beforeDestroy:组件销毁前,

  destroyed:组件成功销毁。

我们通过页面显示和控制台的输出日志来看一下:

当页面加载时会触发 beforeCreate,created,beforeMount,mounted 四个生命周期函数。当执行到 mounted 生命周期函数时,数据才真正挂在到 DOM 上,所以我们从后台获取到的数据可以放在 mounted 生命周期函数中,然后再挂在到 DOM 上。

当我们更改数据时会触发哪些生命周期函数呢,结果如下:

当我们改变数据中的 title 值时,触发了 beforeUpdate 和 updated 生命周期函数。

为了演示 beforeDestroy 和 destroyed 生命周期函数,我们定义了一个子组件,并通过 handleClick() 方法来控制该子组件的挂载和销毁,当我们点击按钮使组件销毁时:

因为我们将 beforeUpdate 和 updated 生命周期函数定义在了父组件上,所以当子组件销毁时也属于父组件更新的一种,所以会触发这两个函数。还触发了 beforeDestroy 和 destroyed 生命周期函数,这两个是在组件销毁时才触发的生命周期函数。

猜你喜欢

转载自www.cnblogs.com/weijiutao/p/10684448.html