[英]How to call a method in vue app from the vue component
我有一個 vue 組件和一個 vue 元素聲明,如下所示
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 中的方法?
您可以像這樣執行根實例方法: 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");
}
}
})
另一個我認為更符合Vuejs架構的解決方案,它是在子組件與其父組件之間使用事件偵聽器和發射器進行通信。
檢查這個簡單的小提琴作為一個願景
Vue.component('todo-item', {
template: '<li>This is a todo</li>',
methods: {
test: function() {
console.log('Emmit this Event.');
this.$emit('yourevent');
}
},
created() {
this.test();
}
});
new Vue({
el: '#vue-app',
data: {
'message': '',
},
methods: {
aNewFunction(event) {
console.log('yourevent Is Triggered!');
this.message = 'Do Stuff...';
},
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.