[英]Vue.JS: Why won't parent element receive event? Does parent have to be a custom component?
[英]Watcher in vue.js won't receive value
我在 vue 中使用观察者来更新组件Persons.vue中的值,只要数组从App.vue传递到Persons.vue作为道具更改。 当我使用选项列表更新道具时,它工作正常并更新。 但是,一旦我使用 datepicker 设置新日期,保存到 prop personData 的数组就会在控制台日志中正确更新,但不会在观察者中收到。
非常感谢任何解决此问题的提示!
这是基于更大应用程序的虚构代码设置,但我希望你能解决问题。
应用程序.vue
<template>
<div id="app">
<select @change="person($event)">
<option :value="selectionOne">One</option>
<option :value="selectionTwo">Two</option>
</select>
<flat-pickr v-model="initDate" :config="config" @on-change="changeTime"></flat-pickr>
</div>
</template>
如果我从更新人员开始,则该值将正确发送给观察者,但如果我之后通过更改日期来运行 changeTime function,则该值不会发送给观察者
data() {
return {
selected: "selectionOne",
selectionOne: "selectionOne",
selectionTwo: "selectionTwo",
personOne: [{ firstName: "XX" }, { born: "XXXX" }],
personTwo: [{ firstName: "YY" }, { born: "YYYY" }],
personData: []
};
},
created() {
this.personData = [{ firstName: "XX" }, { born: "XXXX" }];
},
methods: {
// if I start with updating the person the value is sent to the watcher correctly
person(e) {
this.selected = e;
this.updateNames(e);
},
// but if I after that is running the changeTime function by changing the date the value is not sent to the watcher
changeTime(selectedDates) {
this.born = this.timeFormatter(selectedDates[0]);
this.updateNames(this.selected);
},
updateNames(e) {
this.selected = e;
let selection = e.target.value.split(",");
if (selection == "selectionOne") {
this.personData = this.personOne;
// updating the second position with new born object
this.personData[1] = { born: this.born };
}
if (selection == "selectionTwo") {
this.personData = this.personTwo;
this.personData[1] = { born: this.born };
}
console.log(this.personData)
}
}
};
人物.vue
export default {
name: "Persons",
props: {
personData: {
type: Array
}
},
watch: {
personData: {
deep: true,
immediate: true,
handler(newValue) {
try {
console.log("newValue", newValue);
} catch (err) {
console.log("no data yet ...");
}
}
}
}
};
</script>
您可以尝试使用this.$set
,如下所示:
updateNames(e) {
this.selected = e;
let selection = e.target.value.split(",");
if (selection == "selectionOne") {
this.personData = this.personOne;
// updating the second position with new born object
this.$set(this.personData, 1, { born: this.born });
}
if (selection == "selectionTwo") {
this.personData = this.personTwo;
this.$set(this.personData, 1, { born: this.born });
}
console.log(this.personData)
}
但您可能需要重新评估您的设置。 将数据作为 object 存储在一个数组中,从另一个数组复制,似乎是处理这些数据的一种繁琐方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.