【问题标题】:Receive WebSockets data from vuex and Vue-native-websocket plugin从 vuex 和 Vue-native-websocket 插件接收 WebSockets 数据
【发布时间】:2019-12-18 10:34:23
【问题描述】:

我目前正在使用包含 Vue 和 Vuex 的 Quasar V1 框架。 今天我在看这个插件: https://www.npmjs.com/package/vue-native-websocket/v/2.0.6

我不确定如何设置这个插件并使其工作,需要一点帮助来确保我做对了,因为这将是我第一次将 WebSockets 与 Vue 一起使用。

我首先通过 npm 安装了 vue-native-websocket 并创建了一个名为 src\boot\websocket.js 的引导文件

通过这个命令:

npm install vue-native-websocket --save

websocket.js

import VueNativeSock from 'vue-native-websocket';

export default async ({ Vue }) => {
  Vue.use(VueNativeSock, 'wss://echo.websocket.org', {
    reconnection: true,
    reconnectionAttempts: 5,
    reconnectionDelay: 3000
  });
};

在 Quasar v1 中,我随后在以下位置创建了一个名为“websockets”的模块:

src\store\websockets

这个模块有:

actions.js
getters.js
index.js
mutations.js
state.js

我需要使用格式为 'json' 的 websocket

我的问题是:

假设我有一个页面,我希望在其中创建我的 websocket 连接并接收实时数据,我应该这样做吗?

模块代码: websockets/mutations.js:

export function SOCKET_ONOPEN (state, event) {
  let vm = this;
  vm.prototype.$socket = event.currentTarget;
  state.socket.isConnected = true;
}
export function SOCKET_ONCLOSE (state, event) {
  state.socket.isConnected = false;
}
export function SOCKET_ONERROR (state, event) {
  console.error(state, event);
}
// default handler called for all methods
export function SOCKET_ONMESSAGE (state, message) {
  state.socket.message = message;
}
// mutations for reconnect methods
export function SOCKET_RECONNECT (state, count) {
  console.info(state, count);
}
export function SOCKET_RECONNECT_ERROR (state) {
  state.socket.reconnectError = true;
}

模块代码: websockets/state.js

export default {
  socket: {
    isConnected: false,
    message: '',
    reconnectError: false
  }
};

但现在问题出在我的 vue 页面中。

假设我只想显示来自 websocket 的具有特定事件的数据,请问如何从 vue 页面本身调用它?我对插件的这一部分很困惑。

了解如何分离接收和发送数据对我来说非常重要。 ie:我可能想收到很多用户的列表 或者我可能想收到所有新闻的列表 或者我可以在数据库中添加一个新用户。

我不断听到有关频道、活动和订阅的消息...... 据我了解,您必须先订阅一个频道(即:wss://mywebsite.com/news),然后监听事件,在这种情况下,我相信事件只是来自该频道的数据流)。

如果我对上述内容正确,请问如何订阅频道并使用此插件收听事件,有什么想法吗?

如果你有一个非常简单的例子,那就太好了,谢谢。

【问题讨论】:

    标签: vue.js websocket socket.io vuex


    【解决方案1】:

    我使用 Vue-native-websocket 插件开发了一个聊天应用程序。在这里,我将展示如何在 vuex 商店中注册 pulgin 以及如何从 vue 组件中调用它。

    第 1 步:在您的 index.js file 中定义这些方法

    
    const connectWS = () => {
      vm.$connect()
    }
    const disconnectWS = () => {
      vm.$disconnect()
    }
    
    const sendMessageWS = (data) => {
      if (!Vue.prototype.$socket) {
        return
      }
      Vue.prototype.$socket.send(JSON.stringify(data))
    }
    

    第 2 步:编写套接字状态和突变

    SOCKET_ONOPEN (state, event) {
      if (!state.socket.isConnected) {
          Vue.prototype.$socket = event.currentTarget
          state.socket.isConnected = true
          let phone = state.config.selectedChatTicket.phone
          sendMessageWS({type: WSMessageTypes.HANDSHAKE, data: {id: window.ACCOUNT_INFO.accId, phone: phone, agentId: USER_NAME}})
        }
    },
    SOCKET_ONCLOSE (state, event) {
      console.log('SOCKET_ONCLOSE', state, event)
      state.socket.isConnected = false
      Vue.prototype.$socket = null
    },
    

    // NOTE: Here you are getting the message from the socket connection

    SOCKET_ONMESSAGE (state, message) {   
     state.data.chatCollection = updateChatCollection(state.data.chatCollection,message)
    },
    

    第 3 步:编写 Action,您可以从您的 vue 组件中调用它

    NOTE:: socket actions to connect and disconnect

    WSConnect ({commit, state}) {
      connectWS()
    },
    WSDisconnect ({commit, state}) {
      disconnectWS()
    },
    

    第 4 步:最后注册插件,因为它需要 store 对象

    Vue.use(VueNativeSock, `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://www.example.com/socketserver`,
      { store: store, format: 'json', connectManually: true })
    

    第 5 步:从您的 vue 组件调用您的操作

    buttonClick (rowData) {        
       const tickCount = this.ticketClickCounter
       if (tickCount === 0) {
          this.$store.dispatch('WSConnect')
       } else {
          this.$store.dispatch('WSDisconnect')
           setTimeout(() => {
              this.$store.dispatch('WSConnect')
            }, 1000)
        }
       this.ticketClickCounter = tickCount + 1
    },
    

    现在您已连接到套接字

    第 6 步:在你的 vuex 文件中编写一个动作方法

    sendChatMessageAction ({commit, state}, data) {
          // NOTE: Here, you are sending the message through the socket connection
       sendMessageWS({
            type: WSMessageTypes.MESSAGE,
            data: {
              param1: abc,
              param2: xyz,
              param3: 123,
              param4: $$$
           }
       })
    },
    

    第 7 步:您可以定义一个输入文本框,并在输入事件监听器时调用操作方法

    onEnter (event) {        
     if (event.target.value !== '') {
        let newValue = {
            param1: Date.now(),
            param2: xyz,
            param3: 123,
         }
         this.$store.dispatch('sendChatMessageAction', newValue) // Action
      }
    },
    

    【讨论】:

    • 谢谢,因为这是一个旧线程,所以我一直遵循与您相同的路径(几个月前)。我会将您的回复添加为正确的回复以帮助其他人。
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2017-11-04
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多