2017-02-24 80 views
3

我有一個在父組件中初始化的方法,名爲setMessage(),我希望能夠在子組件中調用它。在vue中使用父函數的子組件js

main.js

const messageBoard = new Vue({ 
    el: '#message-board', 
    render: h => h(App), 
}) 

應用(App.vue(父))..

export default { 
    data() { 
     return { messages: state } 
    }, 
    methods: { 
     setMessage(message) { 
      console.log(message); 
     } 
    }, 
    template: ` 
     <div> 
      <child-component></child-component> 
     </div> 
    `, 
} 

孩子

const child = Vue.extend({ 
    mounted() { 
     // attempting to use this function from the parent 
     this.$dispatch('setMessage', 'HEY THIS IS MY MESSAGE!'); 
    } 
}); 
Vue.component('child-component', child); 

現在我得到this.$dispatch is not a function錯誤消息。我究竟做錯了什麼?我怎樣才能在各種子組件中使用父功能?我也試過$emit,它不會拋出錯誤&它不會觸及該函數。

非常感謝您的幫助!

+0

您使用的是哪個版本的Vue? – Peter

+0

@Peter'2.1.10' – Modelesq

回答

7

你有幾個選項。

方案1 - 從孩子

最簡單的方法是使用this.$parent從你的孩子組件引用$父。事情是這樣的:

const Child = Vue.extend({ 
    mounted() { 
    this.$parent.setMessage("child component mounted"); 
    } 
}) 

選擇2 - 發射事件,在父母

處理,但強烈的夫婦孩子其父。爲了解決這個問題,你可以在兒童中使用$emit事件並讓父母處理它。就像這樣:

const ChildComponent = Vue.extend({ 
    mounted() { 
    this.$emit("message", "child component mounted (emitted)"); 
    } 
}) 

// in the parent component template 
<child-component @message="setMessage"></child-component> 

選擇3 - 中央事件總線

最後一個選項,如果您的組件沒有直接的父子關係,是使用一個單獨的Vue的實例作爲中央活動巴士as described in the Guide。這將是這個樣子:

const bus = new Vue({}); 

const ChildComponent = Vue.extend({ 
    mounted() { 
    bus.$emit("message-bus", "child component mounted (on the bus)"); 
    } 
}) 

const app = new Vue({ 
    ... 
    methods: { 
    setMessage(message) { 
     console.log(message); 
    } 
    }, 
    created() { 
    bus.$on('message-bus', this.setMessage) 
    }, 
    destroyed() { 
    bus.$off('message-bus', this.setMessage) 
    } 
}); 

更新(選項2a) - 通過setMessage爲道具

要跟進您的評論,這裏是它如何工作,通過setMessage到子組件作爲道具:

const ChildComponent = Vue.extend({ 
    props: ["messageHandler"], 
    mounted() { 
    this.messageHandler('from message handler'); 
    } 
}) 

// parent template (note the naming of the prop) 
<child-component :message-handler="setMessage"></child-component> 
+0

嗯。這工作。但是,我擔心我應該讓孩子的組件成爲父母並重用相同的功能。它最終會看起來像'this。$ parent。$ parent.setMessage()'?因此很難追蹤。 – Modelesq

+0

我更喜歡第二種選擇。它與將'setMessage'作爲道具引入不同嗎?這似乎也不起作用;它不會拋出任何有用的錯誤。 – Modelesq

+0

我沒有想過將這個函數作爲道具傳遞,但這將是另一種選擇。只是爲此添加了一個代碼示例...注意道具的連字符名稱以及綁定的事實。 – Peter