vuejs 从子组件更新父数据

新手上路,请多包涵

我开始玩 vuejs (2.0)。我构建了一个包含一个组件的简单页面。该页面有一个带有数据的 Vue 实例。在该页面上,我注册并将组件添加到 html。该组件有一个 input[type=text] 。我希望该值反映在父级(主 Vue 实例)上。

如何正确更新组件的父数据?从父级传递绑定的道具并不好,并向控制台抛出一些警告。他们的文档中有一些东西,但它不起作用。

原文由 Gal Ziv 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 360
2 个回答

双向绑定在 Vue 2.0 中已被弃用,以支持使用更多事件驱动的架构。一般来说,孩子不应该改变它的道具。相反,它应该 $emit 事件并让父级响应这些事件。

在您的特定情况下,您可以使用带有 v-model 的自定义组件。这是一种特殊的语法,允许接近双向绑定,但实际上是上述事件驱动架构的简写。你可以在这里阅读 -> https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events

这是一个简单的例子:

 Vue.component('child', {
  template: '#child',

  //The child has a prop named 'value'. v-model will automatically bind to this prop
  props: ['value'],
  methods: {
    updateValue: function (value) {
      this.$emit('input', value);
    }
  }
});

new Vue({
  el: '#app',
  data: {
    parentValue: 'hello'
  }
});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <p>Parent value: {{parentValue}}</p>
  <child v-model="parentValue"></child>
</div>

<template id="child">
   <input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)">
</template>

文档指出

<custom-input v-bind:value="something" v-on:input="something = arguments[0]"></custom-input>

相当于

<custom-input v-model="something"></custom-input>

这就是为什么孩子身上的道具需要命名为 value,为什么孩子需要 $emit 一个名为 input 的事件。

原文由 asemahle 发布,翻译遵循 CC BY-SA 4.0 许可协议

在子组件中:

 this.$emit('eventname', this.variable)

在父组件中:

 <component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}

原文由 Sarvar N 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题