如何避免Vue的mixin中的共享变量

时间:2019-11-20 12:49:27

标签: vuejs2 vue-component

像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;
}

onOpenlisten是在两个不同的Vue实例中定义的,它们在同一页面上一起工作,并且各自拥有自己的onOpenonmessage

var myApp1 = new Vue({
   …
   mixin: [MyMixin],
   created: function () {
    this.setupWebsocket(this.wsPath);
   },
   methods: {
     onOpen: function(){...},
     …
   }

问题是$socket被共享,并且两个实例将从第二个实例(稍后创建)接收相同的onOpenlisten。我每个实例都需要一个自定义onopen

1 个答案:

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