将方法从父组件传递到vuejs中的子组件

时间:2016-08-31 03:32:08

标签: methods vue.js

有人可以帮助我将方法从父级传递给vue.js中的子组件吗?我一直试图通过将方法作为道具传递来实现...

我的父组件片段:

methods: { 

    test: function () {
        console.log('from test method')
    }

}

<template>
    <child-component test="test"><child-component>
</template>

子组件代码段

created: {
    this.test() //returns test is not a function
},

props: ['test']

有人可以帮忙吗?

提前致谢!

2 个答案:

答案 0 :(得分:19)

您正尝试按照here所述的文字传递函数。您最终将test prop作为String ...您应该使用:来指示动态绑定,如下所示:

<child-component :test="test"><child-component>"

答案 1 :(得分:1)

这很简单。不需要道具。 从您孩子的组件中调用this.$parent.test();

created: {
    this.$parent.test() //calls function test() in parent
},