11

我有这个代码:

     new Vue({
        el: '#app',
        components: {
            'app-component': AppComponent
        },
        data: {
            message: 'Hello Vue.js!'
        },
        methods: {
            doSomething: function(){
                console.log('arrived!')
            }
        }
    })

如何从 AppComponent html 模板调用“doSomething”方法?像这样:

<app-component>  
    <a href="#" v-on:click="doSomething()">text</a>
</app-component>

我收到此错误:

未捕获的类型错误:scope.doSomething 不是函数

4

4 回答 4

12

尝试v-on:click="$parent.doSomething()"

于 2016-05-15T06:42:24.723 回答
2

您可以根据这个答案使用它。

this.$parent.$options.methods.someParentMethod(data)
于 2016-10-01T08:46:38.363 回答
1

您可以使用来自孩子的 $dispatch 来触发事件。例子:

// App component
<app-component>  
    <a href="#" v-on:click.prevent="$dispatch('do-something')">text</a>
</app-component>


// Parent
new Vue({
    el: '#app',
    components: {
        'app-component': AppComponent
    },
    data: {
        message: 'Hello Vue.js!'
    },
    events: {
        'do-something': function(){
            console.log('arrived!')
        }
    }
});

有关父子通信的更多信息,请查看文档:http: //vuejs.org/guide/components.html#Parent-Child-Communication

于 2016-05-14T11:28:16.777 回答
0

除了 Wiljan 响应之外,我还使用具有方法和数据的新 Vue 实例扩展了所有组件。现在我访问方法等。

于 2016-05-14T14:36:17.660 回答