开始使用一个小型的vuejs应用程序.如何在根组件中打开websocket连接,并在其他组件中重用相同的连接?

我希望组件能够通过相同的连接发送和接收.

应用程序.vue:

<template>
  <div id="app">
    <h1>My app</h1>
    <router-link to="/">P&L</router-link>
    <router-link to="/other-page">other page</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {

  name: 'app',
  data () {
    return {
      ws: null
    }
  },

  created () {
    this.ws = new WebSocket('ws://localhost:8123/ws')
  },
  methods: {
    }
  }
}
</script>

现在我想重复使用other-page中的ws,这样就不会在每次改变路由时重新连接.

推荐答案

创建新的js文件(比如"/services/ws.js").创建websocket的实例.

const WS = new WebSocket('ws://localhost:8080');
export default WS;

然后在Vue组件中导入它.

<script>
 import WS from '../services/ws';

 export default {
   // here WS is your websocket instance
 }
 </script>

This is a simpliest way to share data between components (here you simply share WS instance created in another module). You also can fit MVC-style on it, keeping all logic in controllers (other modules) instead of Vue methods.

Vue.js相关问答推荐

用于循环数组的模板元素内的条件渲染

如何只提取一次用于无线电组过滤的数据,而不是针对数据库中的每个条目提取数据?

如何 for each 动态创建的按钮/文本字段设置唯一变量?

组合 API | Vue 路由参数没有被监视

在组件之间共享 websocket 连接

webpack vue-loader 配置

避免在运行时向 Vue 实例或其根 $data 添加响应式属性

如何将 axios/axios 拦截器全局附加到 Nuxt?

正确实现 Vue.js + DataTables

Vuejs 2,VUEX,编辑数据时的数据绑定

Laravel Blade 模板将数据传递给 Vue JS 组件

如何打破 vue.js 中的 v-for 循环?

如何在 vue.config.js 中为生产设置 API 路径?

Vuex:无法读取未定义的属性'$store'

未在实例上定义,但在渲染期间引用

如何在 vue.js 中进行嵌入?

如何在 Promise 回调中更新 Vue 应用程序或组件的属性?

使用 CloudFront 部署在 S3 上的 VueJS 应用程序的指定的密钥不存在

如何使用vue js判断组件本身的数据何时发生变化?

使用 vuex-persistedstate 仅使一个模块持久化