[英]how to share data between components in VUE js (while creating list)
您能否告诉我如何在VUE js中的组件之间共享数据(创建列表时)。我有两个组件list components
和add todo component
。我想在用户单击add button
时在列表中添加项目。但是问题是输入字段存在于不同的组件中,列表存在于不同的组件中,这是我的代码https://plnkr.co/edit/bjsVWU6lrWdp2a2CjamQ?p=preview
//代码在这里
var MyComponent = Vue.extend({
template: '#todo-template',
props: ['items']
});
var AddTODO = Vue.extend({
template: '#add-todo',
props: ['m'],
data: function () {
return {
message: ''
}
},
methods: {
addTodo: function () {
console.log(this.message)
console.log(this.m);
//this.m =this.message;
},
},
});
Vue.component('my-component', MyComponent);
Vue.component('add-todo', AddTODO)
var app = new Vue({
el: '#App',
data: {
message: '',
items: []
},
});
拥有出色的MVVM框架的全部要点是让您拥有视图模型:页面/应用程序/所有内容中所有状态的中央存储。 组件可以发出事件。 您可以拥有事件总线。 但是,如果您可以使用包含您所有状态的简单全局变量来节省一天的时间,那么这是迄今为止最干净,最好的解决方案。 因此,只需将待办事项放在一个数组中,全局范围内的变量中,然后在需要它们的每个组件的data
中声明它们即可。 它在Plunkr中工作 。
标记
<div id="App" >
<add-todo></add-todo>
<my-component></my-component>
</div>
<template id="add-todo">
<div>
<input type="text" v-model="message">
<button @click="addTodo">Add todo</button>
</div>
</template>
<template id="todo-template">
<div>
<ul >
<li v-for="(item,index) in store.items">
{{item.message}}
</li>
</ul>
</div>
</template>
<script src="vue.js"></script>
<script src="script.js"></script>
码
// This is the magic store. This is all you need.
var vueStore = {items : []};
var MyComponent = Vue.extend({
template: '#todo-template',
data : function(){return {store : vueStore}}
});
var AddTODO = Vue.extend({
template: '#add-todo',
data: function () {
return {
message: '',
store : vueStore
}
},
methods: {
addTodo: function (event) {
this.store.items.push({'message' : this.message})
},
},
});
Vue.component('my-component', MyComponent);
Vue.component('add-todo', AddTODO)
var app = new Vue({
el: '#App',
data: {
store : vueStore
},
});
这不是野蛮的骇客! 我们被要求停止考虑事件,向上移动食物链并考虑反应性管道。 组件不在乎何时或由谁更新中央存储。 Vue会照顾好它。
这是状态管理页面。
因此,您可以使用事件并将创建的待办事项发送到根vue实例。 我编辑/分叉了您的朋克(我是小提琴类型)。
https://plnkr.co/edit/bnMiDmi30vsj3a8uROBK?p=preview
因此,我在这里编辑了此行,它侦听added
的自定义事件,并将第一个参数推送到项目。
<add-todo v-on:added='items.push(arguments[0])'></add-todo>
以及发出事件的这些行。 我从属性m
更改为data message
,因为您不应该更改props:
<input type="text" v-model="message">
<button @click="$emit('added', message)">Add todo</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.