![](/img/trans.png)
[英]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.