簡體   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