我开始使用vuejs (2.0)。我构建了一个包含一个组件的简单页面。该页面有一个包含数据的Vue实例。在该页面上,我注册了组件并将其添加到html。该组件有一个input[type=text]
。我希望该值反映在父对象(主Vue实例)上。
如何正确更新组件的父数据?从父级传递绑定的道具并不好,并且会向控制台抛出一些警告。他们的文档中有一些东西,但它不起作用。
发布于 2018-09-09 18:15:50
在子组件中:
this.$emit('eventname', this.variable)
在父组件中:
<component @eventname="updateparent"></component>
methods: {
updateparent(variable) {
this.parentvariable = variable
}
}
发布于 2018-03-23 21:46:27
也可以将道具作为Object或Array进行传递。在这种情况下,数据将是双向绑定的:
(这在主题的末尾注明:https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow )
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;
}
}
});
<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>
发布于 2019-12-27 00:29:12
正确的方法是$emit()
an event in the child component that the main Vue instance listens for。
// 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
}
}
});
https://stackoverflow.com/questions/40915436
复制相似问题