如何在不同的Vue组件上同时使用SocketIO事件

时间:2019-10-14 09:39:11

标签: vue.js socket.io

我有3个组成部分。 App.vue,Header.vue和Example.vue

App.vue是我的父组件。 Header.vue和Example.vue是我的子组件。

我的Header.vue created()方法:

created()
{
   socket.on('notification', data => {
     console.log('Header Page');
   });
}

我的Example.vue created()方法:

created()
{
   socket.on('notification', data => {
     console.log('Example Page');
   });
}

呈现页面时,我在控制台上仅看到“示例页面” 。 具有相同名称的事件仅触发最后一个事件。

这是简单的示例。我使用Vue路由器,仅使用套接字App.vue。对于不同的操作,我检查路由器名称。这非常困难和复杂。

我想在不同的组件上使用具有相同事件名称的不同操作。

我想要这样的输出:

 Header Page
 Example Page

1 个答案:

答案 0 :(得分:0)

可以在Vue js中使用mixins

只需在src目录中创建一个文件mixin.js

mixin.js

const myMixin = (value) => {
    return {
      created(){
        if (value) console.log(value);
      }
    }
}

export default myMixin;

在Header.vue中,导入mixin.js文件

<script>
import myMixin from '../mixin.js';

export default {
    name: 'header-component',
    mixins: [myMixin("header page")],
  };
</script>

在Example.vue中,导入mixin.js文件

<script>
import myMixin from '../mixin.js';

export default {
    name: 'example-component',
    mixins: [myMixin("example page")],
  };
</script>