首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >vuejs从子组件更新父数据

vuejs从子组件更新父数据
EN

Stack Overflow用户
提问于 2016-12-02 00:16:13
回答 7查看 206.3K关注 0票数 210

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

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

EN

回答 7

Stack Overflow用户

发布于 2018-09-09 18:15:50

在子组件中:

代码语言:javascript
复制
this.$emit('eventname', this.variable)

在父组件中:

代码语言:javascript
复制
<component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}
票数 167
EN

Stack Overflow用户

发布于 2018-03-23 21:46:27

也可以将道具作为Object或Array进行传递。在这种情况下,数据将是双向绑定的:

(这在主题的末尾注明:https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow )

代码语言:javascript
复制
Vue.component('child', {
  template: '#child',
  props: {post: Object},
  methods: {
    updateValue: function () {
      this.$emit('changed');
    }
  }
});

new Vue({
  el: '#app',
  data: {
    post: {msg: 'hello'},
    changed: false
  },
  methods: {
    saveChanges() {
        this.changed = true;
    }
  }
});
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <p>Parent value: {{post.msg}}</p>
  <p v-if="changed == true">Parent msg: Data been changed - received signal from child!</p>
  <child :post="post" v-on:changed="saveChanges"></child>
</div>

<template id="child">
   <input type="text" v-model="post.msg" v-on:input="updateValue()">
</template>

票数 7
EN

Stack Overflow用户

发布于 2019-12-27 00:29:12

正确的方法是$emit() an event in the child component that the main Vue instance listens for

代码语言:javascript
复制
// Child.js
Vue.component('child', {
  methods: {
    notifyParent: function() {
      this.$emit('my-event', 42);
    }
  }
});

// Parent.js
Vue.component('parent', {
  template: '<child v-on:my-event="onEvent($event)"></child>',
  methods: {
    onEvent: function(ev) {
      v; // 42
    }
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40915436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档