[英]Updating parent data via child component?
通過子組件更新父數據的正確程序是什么?
在子組件中-我直接通過props
修改父數據。 我不確定這是否是錯誤的解決方法。
根據vue文檔:
當父級屬性更新時,它將流向子級, 但 不會反過來。
子組件示例:
<script>
export default {
props: ['user'],
data: function () {
return {
linkName: '',
linkValue: '',
}
},
methods: {
addLink: function (event) {
event.preventDefault();
this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => {
this.user.links.push(response.data);
}, response => {
// Error
}
});
},
}
}
</script>
我用過this.user.links.push(response.data);
它通過props: ['user']
直接將數據修改到父組件props: ['user']
就像您正確說的那樣, props
並不意味着將數據從孩子傳遞給父母。 數據綁定是單向的。
正確的過程是讓子組件通過$ emit向父組件發送事件以及一些值(可選)。
您可以在子組件的addLink
方法中執行以下操作:
this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => {
this.$emit("update-user-links", response.data); // Send an event to parent, with data
}, response => {
// Error
});
您的父母可以聽以下內容:
<my-user-link-component :user="userData" v-on:update-user-links="addUserLink"></my-user-link-component>
或簡寫語法:
<my-user-link-component :user="userData" @update-user-links="addUserLink"></my-user-link-component>
在上面,您正在分配方法addUserLink
來處理子組件的事件。 在父組件中,您需要按以下方式定義此方法:
methods: {
// ... your other methods,
addUserLink: function(linkData) {
this.userData.links.push(linkData);
}
}
這種從上到下的單向綁定和事件機制的好處:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.