无法将函数从组件分派到父 Vue
Cannot dispatch function from component to parent Vue
我有一个简单的 Vue 演示,可以在用户单击按钮时显示一个模式:
http://plnkr.co/edit/lZPD7HOjKFsNVNmnWAOB?p=preview
问题是,我也在尝试使用一个插件来生成一个 QR 代码,该代码将进入模式内部,所以我在我的组件中设置了一个方法,该方法使用 $dispatch
来调用函数调用 showQR
:
methods: {
showQR: function(){
console.log("Dispatching event for QR code")
this.$dispatch('showQR');
return this.showModal = true
}
}
我的父 Vue 对象中的函数如下所示:
new Vue({
el: 'body',
events: {
showQR: function(){
console.log("Inside the parent Vue")
new QRCode(document.getElementById("qrcode"), "http://whosebug.com/");
}
}
});
我确实从组件中收到消息 "Dispatching event for QR code"
,但父 Vue 上的功能无法正常工作。如果我将逻辑放在模板中,我可以让二维码显示出来,但我宁愿避免这种情况。关于如何使 $dispatch
工作的任何建议?我的目标是正确的 Vue 吗?顺便说一句,使用 VueRouter。任何帮助都会很棒!
看起来你的主要应用程序逻辑被这个覆盖了:
var App = Vue.extend({
template: '<router-view></router-view>'
})
如果将主要方法对象与此扩展结合使用,应该没问题。所以,这样的事情会起作用:
var App = Vue.extend({
el: 'body',
events: {
showQR: function(){
console.log("Inside the parent Vue")
new QRCode(document.getElementById("qrcode"), "http://whosebug.com/");
}
},
template: '<router-view></router-view>'
})
您也很可能不会 want/need el: 'body',
在那里。
我有一个简单的 Vue 演示,可以在用户单击按钮时显示一个模式:
http://plnkr.co/edit/lZPD7HOjKFsNVNmnWAOB?p=preview
问题是,我也在尝试使用一个插件来生成一个 QR 代码,该代码将进入模式内部,所以我在我的组件中设置了一个方法,该方法使用 $dispatch
来调用函数调用 showQR
:
methods: {
showQR: function(){
console.log("Dispatching event for QR code")
this.$dispatch('showQR');
return this.showModal = true
}
}
我的父 Vue 对象中的函数如下所示:
new Vue({
el: 'body',
events: {
showQR: function(){
console.log("Inside the parent Vue")
new QRCode(document.getElementById("qrcode"), "http://whosebug.com/");
}
}
});
我确实从组件中收到消息 "Dispatching event for QR code"
,但父 Vue 上的功能无法正常工作。如果我将逻辑放在模板中,我可以让二维码显示出来,但我宁愿避免这种情况。关于如何使 $dispatch
工作的任何建议?我的目标是正确的 Vue 吗?顺便说一句,使用 VueRouter。任何帮助都会很棒!
看起来你的主要应用程序逻辑被这个覆盖了:
var App = Vue.extend({
template: '<router-view></router-view>'
})
如果将主要方法对象与此扩展结合使用,应该没问题。所以,这样的事情会起作用:
var App = Vue.extend({
el: 'body',
events: {
showQR: function(){
console.log("Inside the parent Vue")
new QRCode(document.getElementById("qrcode"), "http://whosebug.com/");
}
},
template: '<router-view></router-view>'
})
您也很可能不会 want/need el: 'body',
在那里。