为什么在 beforeCreated/created/beforeMount 中更改数据无法在 VUE 中触发监视?
<template>
<div>
<titi :namer="parentName"></titi>
</div>
</template>
<script>
export default {
components: {
titi: {
template: "<h1>{{namer}}</h1>",
props: ["namer"],
watch: {
namer: {
immediate: false,
handler(val, oldVal) {
console.log("jackieyin", val);
}
}
},
mounted() {
console.log("jackieyin", "mounted");
}
}
},
data: function() {
return {
parentName: "jackieyin"
};
},
beforeCreate() {
console.log(222);
this.parentName = "sunwukong";
},
created() {
this.parentName = "kewu";
},
beforeMount() {
this.parentName = "tangseng";
},
mounted() {
// var that = this;
// this.parentName = "tyty";
// setTimeout(() => {
// that.parentName = "shaseng";
// }, 500);
}
};
</script>
我尝试在这些生命周期中更改数据,但无法触发子元素 props 手表。你可以在这里尝试: https://codesandbox.io/s/vue-watch-inx4z
这表现得像我所期望的那样。如果您考虑下面的生命周期顺序,则在父组件上,子组件仅在父组件beforeMount
之后和父组件mounted
之前创建。因此,您在孩子身上的手表不会因父母在beforeCreate
或created
中对道具所做的更改而触发,因为那时孩子不存在。
- 父
beforeCreate
- 父
created
- 父
beforeMount
- 儿童
beforeCreate
- 如果
immediate: true
子观察程序将在此处触发,并传递初始值
- 如果
- 儿童
created
- 儿童
beforeMount
- 儿童
mounted
- 儿童
- 此处对属性的任何更改都将从此解雇儿童观察者
- 父
mounted
在观察程序中,设置immediate: false
监视的值。这意味着,当设置属性的初始值时,它不会触发。如果将其更改为 true,您将看到父组件在中创建子组件时立即触发监视beforeMount
设置的值。此外,如果您在父mounted
生命周期挂钩中再次更改了该值,则无论 immediate
的值如何,子项中的观察程序都会选取该值。