2017-09-02 43 views
0

请问如何在VUE js中的组件之间共享数据(创建列表时)。我有两个组件list componentsadd todo component。我想添加项目在名单上的时候。但add button问题用户点击存在于不同的组件和列表输入字段出现在不同的分量 这里是我的代码 https://plnkr.co/edit/bjsVWU6lrWdp2a2CjamQ?p=preview如何共享VUE js中的组件之间的数据(创建列表时)

//代码放在这里

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: [] 
    }, 


}); 
+0

使用[事件总线](https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication)或VueX。 – Terry

+0

你怎么能分享重拳 – user5711656

回答

0

,所以你可以使用事件和将创建的待办事项发送到根vue实例。 我编辑/分叉您的plunkr(我更喜欢小提琴类型)。

https://plnkr.co/edit/bnMiDmi30vsj3a8uROBK?p=preview

所以我在这里编辑这行,来监听自定义事件added和推动的第一个参数项目。

<add-todo v-on:added='items.push(arguments[0])'></add-todo> 

还有这些行,它们发出事件。我是从属性m改为数据message,因为你不应该变异道具:

<input type="text" v-model="message"> 
    <button @click="$emit('added', message)">Add todo</button> 
2

有一个伟大的MVVM框架的整点是让你有一个视图模型:所有的中央存储在你的页面/应用/任何状态。组件可以发出事件。你可以有一个活动巴士。 但是如果你可以用一个包含你所有状态的简单的全局变量来保存一天,这是迄今为止最干净,最好的解决方案。因此,只需将您的待办事项放在数组中,放入全局范围的变量中,然后在需要它们的每个组件的data中声明它们即可。 Here it is working in 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照顾它。

Here's页面状态管理。