[英]change parent props from child component in vuejs2
我想從子組件中更改父級道具的值。 這在 vuejs 1 中效果很好,但在 vue 2 中效果不佳(我想在 vue.js 2 中使用它)。
這是一個小例子:
<div id="app">
<parent :content="{value:'hello parent'}"><</parent>
</div>
var parent = {
template: '<child :content="content"></child>',
props: ['content'],
};
var child = {
template: '<div>{{ content.value }}<button @click="change">change me</button></div>',
props: ['content'],
methods: {
change() {
this.content.value = "Value changed !";
}
}
};
Vue.component('child', child);
Vue.component('parent', parent);
new Vue({
el: '#app',
});
.sync
修飾符。 在父data
中創建content
道具的本地副本(請參閱此處的原因)。
var parent = {
...
data() {
return {
localContent: this.content // creating a local copy, so we can mutate and react to it
}
}
};
現在,將localContent
傳遞給孩子,而不是content
。 並使用.sync
傳遞它,以便對其進行更新:
var parent = {
template: '<div><child :content.sync="localContent"></child></div>',
... // ^^^^^^^^^^^^^^^^^^^^-- changed here
現在,在孩子中,不要分配給this.content.value
,而是發出更新事件:
var child = {
...
change() {
this.$emit('update:content', {value: "Value changed !"})
}
}
};
這個帶有新值的事件將被父級拾取並更新其localContent
,這也將因此更新子級的content
prop。
下面的最終運行代碼。
var parent = { template: '<div><child :content.sync="localContent"></child><br>At parent: {{ localContent }}</div>', props: ['content'], data() { return { localContent: this.content } } }; var child = { template: '<div>At child: {{ content.value }}<button @click="change">change me</button></div>', props: ['content'], methods: { change() { this.$emit('update:content', {value: "Value changed !"}) } } }; Vue.component('child', child); Vue.component('parent', parent); new Vue({ el: '#app' });
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script> <div id="app"> <parent :content="{value:'hello parent'}"></parent> </div>
您將不得不為此使用發射事件
家長:
<child :content="content" @updateParent="updateValue"></child>
methods: {
updateValue (value) {
// Your code here
}
}
孩子:
props: ['content'],
methods: {
change () {
this.$emit('updateParent', value)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.