2016-11-08 69 views
1

在一個項目vue.js 2:
我有一個組件居住在一個.vue文件,代表一個元素列表。另外,我有一個側欄是這個列表的總結。該側邊欄是.vue文件中的另一個組件。
所以,我怎麼能保持每個間的通信它們,例如,如果我刪除從列表中元素,反映在側邊欄宣佈一個VAR的變化是元素的總數ilustrate:

邊欄.vue如何溝通兩個單獨的.vue文件?

<template> 
    ... 
    <span></span> ===> here I need total of elements listed in ListElements.vue 
    ... 
<template> 

ListElements.vue

<template> 
    ... 
    @click="deleteEntry" 
    ... 
<template> 

<script> 
    methods: { 
     deleteEntry(entry) { 
     //here I need to notify to SideBar.vue in order to update the total of elements in the this.entries list. 
     let index = this.entries.indexOf(entry); 
     if (window.confirm('Are you sure you want to delete this time entry?'))   { 
      this.entries.splice(index, 1); 
     } 
     } 
</script> 
+0

能否請你添加一些代碼(如果可能簡化的),以顯示這個問題? –

+0

這可能會有幫助:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication –

+0

我已經閱讀過這個,但我不知道如何保持相同的實例總線對象跨兩個組件在兩個分離.vue文件 – mos

回答

2

OK,我創建的是如何工作的一個簡單的例子。您總線必須是全球性的,因此是所有Vue組件訪問,這僅僅意味着將它的所有其他組件和視圖模型之外:

var bus = new Vue({}); 

var vm = new Vue({ 
    // Main view model has access to bus 
    el: '#app' 
}); 

然後你只需要發出總線上的事件上的一些事件和捕捉,在其它成分:

元器件一個發射一個消息到總線上KEYUP:

Vue.component('component-one', { 
    template: '<div>Enter a message: <input v-model="msg" v-on:keyup="updateMessage"> </div>', 
    methods: { 
    updateMessage() { 
     bus.$emit('msg', this.msg); 
    } 
    }, 
    data() { 
    return { 
     msg: "" 
    } 
    } 
}); 

元器件個監聽消息:

Vue.component('component-two', { 
    template: "<div><b>Component one says: {{ msg }}</b></div>", 
    created() { 
    bus.$on('msg', (msg) => { 
     this.msg = msg; 
    }); 
    }, 
    data() { 
    return { 
     msg: "" 
    } 
    } 
}); 

這裏的小提琴:https://jsfiddle.net/v7o6d2vL/

對於您的單一頁面組件來獲得訪問你只需要確保你的總線是在全球範圍內,您可以通過使用window做公交車:

window.bus = new Vue({}); 

然後你可以使用bus.$emit()bus.$on()你的組件內正常

+0

所有這些組件都在同一個文件中,我怎樣才能跨多個.vue文件共享總線實例? – mos

+0

是的,對不起。我已經爲你更新了我的答案。 –