gpt4 book ai didi

vue.js - vue中的委托(delegate)事件

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:04 26 4
gpt4 key购买 nike

我试图将一个事件从一个实例委托(delegate)给另一个实例。

我在页面顶部有一个工具栏,上面有一个这样的按钮

<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>

此添加事件在此 vue 实例中工作

var toolbarApp = new Vue({
el: '#toolbar',
data: {

},
methods: {
add: function (event) {
alert('lol');
}
}
});

但现在我想像这样将此添加事件附加到另一个实例

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');
}
}
});

但由于实例不同,我无法附上这个。有什么办法吗?也曾尝试使用 mixin,但没有成功。

多谢指教

最佳答案

你要做的不是唯一的,它甚至有一个标题“事件总线”

EventBus = new Vue();

var toolbarApp = new Vue({
el: '#toolbar',
data: {

},
methods: {
add: function (event) {
EventBus.$emit('add-something', this.somevar);
}
}
});

然后在你的另一个实例中:

var contactApp = new Vue({
mixins: [toolbarApp],
el: '#contact',
data: {
showGrid: true,
showForm: false,
editMode: false
},
created: function () {
this.getContacts();
EventBus.$on('add-something', function(somevar) {
// do cool stuff, like this.getContacts...
});
},
methods: {
getContacts: function () {
$.getJSON(this.apiGrid, function (data) {
this.contacts = data;
}.bind(this));
},
add: function (event) {
alert('hej');
}
}
});

定义:

有时您需要一种快速简便的解决方案来在 Vue.js 组件之间传递数据。

对于具有简单架构的应用程序,使用事件在组件之间进行通信就足够了。为此,我们可以创建一个快速解决方案并实现 EventBus。 EventBus 允许我们在一个组件中发出事件并在另一个组件中监听该事件。

https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860

关于vue.js - vue中的委托(delegate)事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com