[英]Vue watch does not trigger when changing the data value to the same value
[英]Why change data in beforeCreated/created/beforeMount can not trigger watch in VUE?
为什么更改 beforeCreated/created/beforeMount 中的数据不能在 VUE 中触发 watch?
<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
这与我预期的一样。 如果您考虑下面的生命周期顺序,则在父级上,子组件仅在父级上的beforeMount
之后和在父级上mounted
之前创建。 因此,您对子项的监视不会因为对beforeCreate
中所做的或由父项created
的道具的更改而触发,因为此时子项不存在。
beforeCreate
created
beforeMount
beforeCreate
immediate: true
,并传递初始值created
beforeMount
mounted
mounted
在您的观察者中,您在手表上设置了值immediate: false
。 这意味着,当设置属性的初始值时,它不会触发。 如果将其更改为 true,您将看到父级在beforeMount
中设置的值会在创建子组件时立即触发监视。 此外,如果您在父级mounted
的生命周期挂钩中再次更改该值,则无论immediate
的值如何,子级中的观察者都会拾取该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.