我试图将一个事件从一个实例委托给另一个实例。
我在页面顶部有一个工具栏,其中有一个像这样的按钮
<div id="toolbar">
<button v-on:click="add" class="btn btn-default" type="submit"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Ny</button>
</div>
Run Code Online (Sandbox Code Playgroud)
此添加事件在此 vue 实例中工作
var toolbarApp = new Vue({
el: '#toolbar',
data: {
},
methods: {
add: function (event) {
alert('lol');
}
}
});
Run Code Online (Sandbox Code Playgroud)
但现在我想将此添加事件附加到另一个实例,如下所示
var contactApp = new Vue({
mixins: [toolbarApp],
el: '#contact',
data: {
showGrid: true,
showForm: false,
editMode: false
},
created: function () {
this.getContacts();
},
methods: {
getContacts: function () {
$.getJSON(this.apiGrid, function (data) {
this.contacts = data;
}.bind(this));
},
add: function (event) {
alert('hej');
}
}
});
Run Code Online (Sandbox Code Playgroud)
但由于实例不同,我无法附加此内容。有什么办法可以做到这一点吗?也尝试过使用 mixin 但没有运气。
谢谢指教
小智 5
你想做的事情并不独特,甚至有一个标题“事件总线”
\n\nEventBus = new Vue();\n\nvar toolbarApp = new Vue({\n el: \'#toolbar\',\n data: {\n\n },\n methods: {\n add: function (event) {\n EventBus.$emit(\'add-something\', this.somevar);\n }\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n\n然后在你的另一个实例中:
\n\nvar contactApp = new Vue({\n mixins: [toolbarApp],\n el: \'#contact\',\n data: {\n showGrid: true,\n showForm: false,\n editMode: false\n },\n created: function () {\n this.getContacts();\n EventBus.$on(\'add-something\', function(somevar) {\n // do cool stuff, like this.getContacts...\n });\n },\n methods: {\n getContacts: function () {\n $.getJSON(this.apiGrid, function (data) {\n this.contacts = data;\n }.bind(this));\n },\n add: function (event) {\n alert(\'hej\');\n }\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n\n定义:
\n\n有时您需要一个快速简单的解决方案来在 Vue.js 组件之间传递数据。
\n\n对于具有简单架构的应用程序来说,它足以使用事件在组件之间进行通信。为此,我们可以创建一个快速解决方案并实现 EventBus。EventBus 允许我们在一个组件中发出事件并在另一个组件中侦听该事件。
\n\n\n| 归档时间: |
|
| 查看次数: |
2286 次 |
| 最近记录: |