0%

Vue 生命周期的一点补充

data

上面的这幅图描述了 Vue 组件响应式更新的过程,每个组件实例对应一个 watcher 实例,它会在组件渲染的过程中把”接触”过的数据 property 记录为依赖。之后当依赖项的 setter 触发时,会通知 watcher 从而使它关联的组件重新渲染。

需要注意的是 Vue 不会去收集 data 函数中没有在 template 中依赖的数据,当这些数据变化时,组件也不会重新渲染。这里是一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div class="hello">
<button @click="change">change</button>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {
a: 1,
};
},
updated() {
console.log("更新了");
},
methods: {
change() {
this.a += 1;
console.log(this.a);
},
},
};
</script>

在点击 change 按钮后, this.a 会加 1,但是 updated 钩子函数不会执行。因为在 template 中没有用到 this.a