2017-02-24 48 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