Vuejs2 如何避免Vue'中的共享变量;s混合

Vuejs2 如何避免Vue'中的共享变量;s混合,vuejs2,vue-component,Vuejs2,Vue Component,有混合的 var MyMixin = { methods: { setupWebsocket: function (wsPath) { … Vue.use( VueNativeSock.default, url, { reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000,

有混合的

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

我可以这样解决它:

移动
Vue。在创建任何实例之前,在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
在每个vue的实例中,我都可以访问

 instance.$options.sockets
这是一个
代理
。(
$options.sockets
以前不可用)

然后,在创建的实例中,我可以为每个组件设置自定义功能:

 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

我可以这样解决它:

移动
Vue。在创建任何实例之前,在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
在每个vue的实例中,我都可以访问

 instance.$options.sockets
这是一个
代理
。(
$options.sockets
以前不可用)

然后,在创建的实例中,我可以为每个组件设置自定义功能:

 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

它们做的是相同的事情吗?如果他们这样做了,只需在任何首先加载的内容上放置一个条件,如果它存在,则不初始化它。这显然也是通过vue 2(react hooks样式)中的插件提供的新功能/合成api的使用情况。它们做的是相同的事情吗?如果他们这样做了,只需在任何首先加载的内容上放置一个条件,如果它存在,则不初始化它。这显然也是通过vue 2中的插件(react-hooks样式)提供的新功能/合成api的用例