像mixin一样
var MyMixin = {
methods: {
setupWebsocket: function (wsPath) {
…
Vue.use(
VueNativeSock.default, url,
{
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
format: 'json',
}
);
this.$socket.onmessage = this.listen;
this.$socket.onopen = this.onOpen;
}
onOpen
和listen
是在两个不同的Vue实例中定义的,它们在同一页面上一起工作,并且各自拥有自己的onOpen
和onmessage
:
var myApp1 = new Vue({
…
mixin: [MyMixin],
created: function () {
this.setupWebsocket(this.wsPath);
},
methods: {
onOpen: function(){...},
…
}
问题是$socket
被共享,并且两个实例将从第二个实例(稍后创建)接收相同的onOpen
和listen
。我每个实例都需要一个自定义onopen
。
答案 0 :(得分:0)
我能够这样解决:
在创建任何实例之前将Vue.use
移动到mixin之外并运行它
function setupWebSocket(wsPath){
var port = window.location.port;
var domain = window.location.hostname + (port ? ':' + port : '');
var schema = (port ? 'ws' : 'wss') + '://';
var url = schema + domain + '/stream/' + wsPath;
Vue.use(
VueNativeSock.default, url,
{
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
format: 'json',
}
);
}
...
setupWebSocket(wsPath); // plain javascript outside component
上面给了我每个实例的访问权限
instance.$options.sockets
是Proxy
。 ($options.sockets
之前不可用)
然后在created
的实例中,我可以为每个组件设置自定义功能:
instance.$options.sockets.onmessage
instance.$options.sockets.onopen
最终测试:
myApp1.$options == myAppB.$options
false
myApp1.$options.sockets == myAppB.$options.sockets
false
myApp1.$socket == myAppB.$socket
true
现在每个实例都运行自己的自定义onopen