vuejs更新子组件的父数据

vuejs更新子组件的父数据

本文介绍了vuejs更新子组件的父数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting to play with vuejs (2.0).I built a simple page with one component in it.The page has one Vue instance with data.On that page I registered and added the component to html.The component has one input[type=text]. I want that value to reflect on the parent (main Vue instance).

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

How do I correctly update the component's parent data?Passing a bound prop from the parent is not good and throws some warnings to the console. They have something in their doc but it is not working.

推荐答案

在Vue 2.0中不推荐使用双向绑定使用更多事件驱动的架构。一般来说,孩子不应该改变它的道具。相反,它应该。

In your specific case, you could use a custom component with v-model. This is a special syntax which allows for something close to two-way binding, but is actually a shorthand for the event-driven architecture described above. You can read about it here -> https://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>

这就是为什么孩子的道具需要被命名为值,为什么孩子需要$发出名为 input 的事件。

That is why the prop on the child needs to be named value, and why the child needs to $emit an event named input.

这篇关于vuejs更新子组件的父数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:27