1.0.18 • Published 5 years ago
vue-cli-plugin-websocket v1.0.18
vue脚手架插件 -- websocket
该插件是基于Vue Cli 扩展的增加websocket功能。
Install
vue add websocket安装完成之后,会把插件中generator/template目录下的模板文件添加到项目中,项目启动之后可在store中获取socket的连接信息
// 插件目录结构
├── README.md
├── generator  # generator(可选)
  ├── template  # 模板
    ├── src
      ├── store
        ├── modules
          ├── websocket.js
        ├── mutation-types.js
      ├── assets
        ├── js
          ├── websocket.js
  ├── index.js
├── index.js      # service 插件
├── package.json
├── prompts.js    # prompt 文件(可选)
└── ui.js         # Vue UI 集成(可选)tip: 插件安装完成之后,需把assets/js/websocket.js文件中的url替换成项目实际使用的地址
Usage
通过URL自动连接
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:9090')集成Vuex
import store from './store'
Vue.use(VueNativeSock, 'ws://localhost:9090', { store: store })设置 sub-protocol
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:9090', { protocol: 'my-protocol' })启用JSON转换
Vue.use(VueNativeSock, 'ws://localhost:9090', { format: 'json' })message转换成JSON
import store from './store'
Vue.use(VueNativeSock, 'ws://localhost:9090', { store: store, format: 'json' })自动重连
Vue.use(VueNativeSock, 'ws://localhost:9090', {
  reconnection: true, // (Boolean) whether to reconnect automatically (false)
  reconnectionAttempts: 5, // (Number) number of reconnection attempts before giving up (Infinity),
  reconnectionDelay: 3000, // (Number) how long to initially wait before attempting a new (1000)
})手动连接
Vue.use(VueNativeSock, 'ws://localhost:9090', {
  connectManually: true,
})
const vm = new Vue()
// Connect to the websocket target specified in the configuration
vm.$connect()
// Connect to an alternative websocket URL and Options e.g.
vm.$connect('ws://localhost:9090/alternative/connection/', { format: 'json' })
// do stuff with WebSockets
vm.$disconnect()在vue实例中使用
var vm = new Vue({
  methods: {
    clickButton: function(val) {
        // $socket is [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) instance
        this.$socket.send('some data')
        // or with {format: 'json'} enabled
        this.$socket.sendObj({awesome: 'data'})
    }
  }
})动态监听
// 创建监听
this.$options.sockets.onmessage = (data) => console.log(data)
// 删除监听
delete this.$options.sockets.onmessageVuex集成
SOCKET_ONOPEN(开启socket连接)
SOCKET_ONCLOSE (关闭socket连接)
SOCKET_ONERROR (socket异常)
SOCKET_ONMESSAGE (socket消息)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false,
    }
  },
  mutations:{
    SOCKET_ONOPEN (state, event)  {
      Vue.prototype.$socket = event.currentTarget
      state.socket.isConnected = true
    },
    SOCKET_ONCLOSE (state, event)  {
      state.socket.isConnected = false
    },
    SOCKET_ONERROR (state, event)  {
      console.error(state, event)
    },
    // default handler called for all methods
    SOCKET_ONMESSAGE (state, message)  {
      state.socket.message = message
    },
    // mutations for reconnect methods
    SOCKET_RECONNECT(state, count) {
      console.info(state, count)
    },
    SOCKET_RECONNECT_ERROR(state) {
      state.socket.reconnectError = true;
    },
  },
  actions: {
    sendMessage: function(context, message) {
      .....
      Vue.prototype.$socket.send(message)
      .....
    }
  }
})// mutation-types.js
const SOCKET_ONOPEN = '✅ Socket connected!'
const SOCKET_ONCLOSE = '❌ Socket disconnected!'
const SOCKET_ONERROR = '❌ Socket Error!!!'
const SOCKET_ONMESSAGE = 'Websocket message received'
const SOCKET_RECONNECT = 'Websocket reconnected'
const SOCKET_RECONNECT_ERROR = 'Websocket is having issues reconnecting..'
export {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
}
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
import {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
} from './mutation-types'
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false,
    }
  },
  mutations: {
    [SOCKET_ONOPEN](state, event)  {
      state.socket.isConnected = true
    },
    [SOCKET_ONCLOSE](state, event)  {
      state.socket.isConnected = false
    },
    [SOCKET_ONERROR](state, event)  {
      console.error(state, event)
    },
    // default handler called for all methods
    [SOCKET_ONMESSAGE](state, message)  {
      state.socket.message = message
    },
    // mutations for reconnect methods
    [SOCKET_RECONNECT](state, count) {
      console.info(state, count)
    },
    [SOCKET_RECONNECT_ERROR](state) {
      state.socket.reconnectError = true;
    }
  }
})
// index.js
import store from './store'
import {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
} from './mutation-types'
const mutations = {
  SOCKET_ONOPEN,
  SOCKET_ONCLOSE,
  SOCKET_ONERROR,
  SOCKET_ONMESSAGE,
  SOCKET_RECONNECT,
  SOCKET_RECONNECT_ERROR
}
Vue.use(VueNativeSock, 'ws://localhost:9090', {
  store: store,
  mutations: mutations
})