vue使用WebSocket连接

1.在store里面新建ws.js文件

export default {
  state: {
    webst: null,
    WSMessage: null,
    WSStatus: null
  },
  mutations: {
    /**
      * @description 建立websocket连接
      * @param  state vuex state
      * @param  webst webSocket对象
      */
    setConnect (state, webst) {
      state.webst = webst
    },
    /**
      * @description websocket消息
      * @param  state vuex state
      * @param  message webSocket消息
      */
    setMessage (state, message) {
      state.WSMessage = message
    },
    /**
      * @description 设置websocet的状态
      * @param  state vuex state
      * @param  message webSocket消息
      */
    setWSStatus (state, status) {
      state.WSStatus = status
    }
  },
  actions: {
    /**
     *  @description 开启websocket连接
     */
    connect ({ state, commit, dispatch, rootState }, { token }) {
      return new Promise((resolve, reject) => {
        const wsurl = 'websocket连接地址'
        const webs = new WebSocket(wsurl)
        // 客户端接收服务端数据时触发
        webs.onmessage = (e) => {
          commit('setWSStatus', 'success')
          commit('setMessage', e.data)
          // 进行操作...
        }
        // 建立连接时触发
        webs.onopen = (e) => {
          commit('setWSStatus', 'open')
        }
        // 通信发生错误时触发
        webs.onerror = (e) => {
          state.webst.close()
          commit('setWSStatus', 'error')
        }
        // 连接关闭时触发
        webs.onclose = (e) => {
          commit('setWSStatus', 'closed')
        }
        resolve(webs)
      })
    },
    /**
     *  @description 关闭websocket
     */
    close ({ state, commit, dispatch, rootState }) {
      if (state.webst) {
        state.webst.close()
        commit('setWSStatus', 'closed')
        commit('setMessage', null)
        commit('setConnect', null)
      }
    }
  }
}

2.登录时和退出时调用

// 登录
   dispatch('connect', null, { root: true })

// 退出登录
  dispatch('close', null, { root: true })

展示效果
vue使用WebSocket连接_第1张图片

你可能感兴趣的:(vue.js,websocket,javascript)