繁体   English   中英

从 vuejs2 中的子组件更改父道具

[英]change parent props from child component in vuejs2

我想从子组件中更改父级道具的值。 这在 vuejs 1 中效果很好,但在 vue 2 中效果不佳(我想在 vue.js 2 中使用它)。

这是一个小例子:

HTML

<div id="app">
   <parent :content="{value:'hello parent'}"><</parent>
</div>

JavaScript

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',
});

https://jsfiddle.net/f5gt94f2/

tl;dr:在 vue2 中,您需要使用.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)
  }
}

https://v2.vuejs.org/v2/guide/components.html#Custom-Events

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM