为什么更改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>
我尝试在这些生命周期中更改数据,但无法触发子元素道具手表。您可以在这里尝试: https://codesandbox.io/s/vue-watch-inx4z
答案 0 :(得分:2)
这符合我的预期。如果您考虑以下生命周期顺序,则在父级上,子级组件仅在父级上{em> beforeMount
之后,在父级mounted
之前创建。因此,您对孩子的监视不会因为父母在beforeCreate
或created
中所做的道具更改而被解雇,因为此时孩子不存在。
beforeCreate
created
beforeMount
beforeCreate
immediate: true
处触发,并传递初始值created
beforeMount
mounted
mounted
在观察者中,您在手表上设置了值immediate: false
。这意味着,设置属性的初始值时不会触发。如果将其更改为true,则将在创建子组件时看到父beforeMount
中设置的值立即触发监视。另外,如果您在父项mounted
生命周期挂钩中再次更改了该值,则无论immediate
的值如何,子级中的观察者都将选择该值。