如何从 vue 组件调用 vue app 中的方法 [英] How to call a method in vue app from the vue component
本文介绍了如何从 vue 组件调用 vue app 中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 vue 组件和一个 vue 元素声明,如下所示
I have a vue component and a vue element declaration as given below
Vue.component('todo-item', {
template: '<li>This is a todo</li>'
methods: {
test: function() {
// I am getting an error here
app.aNewFunction();
}
}
})
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
aNewFunction: function() {
alert("inside");
}
}
})
如何从vue组件调用vue app中的方法?
How to call a method in vue app from the vue component?
推荐答案
你可以像这样执行根实例方法:this.$root.methodName()
You can execute root instance method like this: this.$root.methodName()
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
this.$root.aNewFunction();
}
},
mounted() {
this.test();
}
})
new Vue({
el: '#app',
template: '<todo-item></todo-item>',
methods: {
aNewFunction: function() {
alert("inside");
}
}
})
这篇关于如何从 vue 组件调用 vue app 中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文