2017-04-25 84 views
0

我有一個父Vue,它啓用或禁用「編輯」模式。在非編輯模式下,所有組件都是隻讀的。Vue:事件方法 - 混亂

我已經通過一個數據對象實現了這一切,並且一切正常。

我已經拆分了一些子組件中的組件。

從父的$放出消息,與新的編輯模式狀態發送:

methods: { 
    toggleMode() { 
     this.editMode = !this.editMode 
     this.$emit('edit-mode-change', this.editMode) 
    } 

使用Vue公司DevTools我可以看到消息發出。

但是,我似乎無法收到它在我的孩子組件!我看過一個文檔,但沒有任何例子符合這種情況。這是我目前有(的子組件):

methods: { 
    onEditModeChange: function (mode) { 
    console.log('mode is', mode) 
    this.editMode = mode 
    } 

也試過:

events: { 
    onEditModeChange: function (mode) { 
    console.log('mode is', mode) 
    this.editMode = mode 
    } 

另外我發現了一個瀏覽器控制檯錯誤如下:

[Vue warn]: Invalid handler for event "edit-mode-change": got false 
(found in <Dimensions> at /home/anthony/Projects/Towers-Vue/src/components/assets/Dimensions.vue) 

我確定我正在做一些基本錯誤的事情,但是文檔沒有引用這些事件:{} block,但是我在其他代碼中看到了它。它也沒有顯示如何實現一個監聽器。

感謝您花時間閱讀本文,如果您能指引我正確的方向,非常感謝。

+0

這是Vue 1還是Vue 2? –

+0

Vue 2.道歉忘記提及這一點。 – Anthony

+0

更多信息:http://www.wapgee.com/story/s/vuejs-forms-two-way-data-binding-and-v-model –

回答

1

在Vue 2中,事件只是橫向或向上流動,而不是向下流動。

你真正想要的只是將一個道具傳遞給你的組件。

在父JS:

toggleMode() { 
    this.editMode = ! this.editMode; 
} 

在父模板:

<child-component-1 :editMode="editMode"></child-component-1> 
...same for others... 

然後簡單地接受editMode在每個子組件的道具:

{ 
    props: ['editMode'] 
} 

你現在可以在孩子的模板中使用editMode。它會跟蹤父母的editMode,所以不需要手動事件/觀察者。

+0

謝謝!這解決了它,再加上它非常簡單,就像Vue的其餘部分一樣。 – Anthony

1

vue2的工作原理是通過使數據的單向流動,從父母到孩子的辦法,所以在你的父組件,你可以有

<template> 
<child-component :isEditing="editMode"></child-component> 
</template> 

<script> 

export default { 
    methods: { 
     toggleMode() { 
      this.editMode = !this.editMode 
      this.$emit('edit-mode-change', this.editMode) 
     } 
    } 
} 

和子組件使用道具來獲得數據

Vue.component('child-component', { 
    props: ['isEditing'], 
    template: '<span>edit mode: {{ isEditing }}</span>' 
}) 

我們已經介紹了孩子的編輯模式。現在,如果你想從孩子到家長髮送數據,則孩子需要「發出」信號給父母,作爲道具的「只讀」

的子組件,你在任何時候

someMethod() { 
    this.$emit('editDone', dataEdited); 
} 

,並在你的父組件你「攔截」的消息上使用:

<template> 
    <child-component 
     :isEditing="editMode" 
     @editDone="someParentMethod"></child-component> 
</template> 

問候!

+0

感謝您的回覆。它幫助更清楚地瞭解事情。 – Anthony

+0

您的方法一定會在以後使用,特別是對於更復雜的父母/孩子互動。目前,我只需要在兒童中啓用編輯模式。但我可以看到父母需要知道孩子狀況的情況。 – Anthony