安装
yarn add vue-native-websocket
# or
npm install vue-native-websocket --save
使用
一、配置
通过URL字符串自动进行websocket连接
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:9090')
二、连接实例
1、自动连接
启用ws自动重新连接(适用于整个系统多方面应用websocket接收消息):
import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
const socketUrl = 'ws://' + window.location.host + '/hh-web/webSocket';
Vue.use(VueNativeSock, socketUrl, {
reconnection: true, // 自动重新连接 (false)
reconnectionAttempts: Infinity, // 重新连接尝试次数 (Infinity),
reconnectionDelay: 2000, // 重新连接时间间隔
})
2、手动连接
启用ws手动连接(适用于系统单个页面接收处理websocket消息):
import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
const socketUrl = 'ws://' + window.location.host + '/hh-web/webSocket';
Vue.use(VueNativeSock, socketUrl, {
connectManually: true, //是否手动连接ws
reconnectionAttempts: Infinity, // 重新连接尝试次数 (Infinity),
reconnectionDelay: 2000, // 重新连接时间间隔
})
3、关于Vuejs实例的用法
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'})
}
}
})
4、创建和删除动态websocket事件监听器
创建一个新的动态监听器
this.$options.sockets.onmessage = (data) => console.log(data)
删除现有监听器
delete this.$options.sockets.onmessage
三、应用实例
自定义websocket事件处理
1、事件名称
2、函数定义
3、原始/默认处理程序代码功能function (eventName, event)。这使您可以选择将事件移交给原始处理程序之前进行一些基本的预处理。
这是执行一些预处理,然后将事件传递到原始处理程序代码的示例:
实例
1、新建websocket/index.js文件
2、在入口函数中引入websocket文件
import { useSocket } from './modules/websocket'
useSocket()
3、编写websocket文件,自定义websocket事件处理
3.1、引入websocket组件、定义常量
import Vue from 'vue'
import VueNativeSock from 'vue-native-websocket'
const socketUrl = 'ws://' + window.location.host + '/hh-web/webSocket';
/* 定义并导出接收socket后触发的自定义在事件名 -- start */
export const debugEvent = 'debugEvent'
/* 定义并导出接收socket后触发的自定义在事件名 -- end */
3.2、定义useSocket函数
let socketBus
function useSocket () {
Vue.use(VueNativeSock, socketUrl, {
reconnection: true, // 自动重新连接 (false)
reconnectionAttempts: Infinity, // 重新连接尝试次数 (Infinity),
reconnectionDelay: 2000, // 重新连接时间间隔
})
socketBus = new Vue() //vue实例,用来绑定动态监听器 onclosed onmessage等事件
socketBus.$options.sockets.onclose = () => {
console.log('websocket closed')
}
socketBus.$options.sockets.onmessage = (e) => {
let data
try {
data = JSON.parse(e.data)
} catch (e) {
console.log(e)
data = null
}
handleSocketData(data) //数据处理函数
}
}
3.3、编写数据处理函数
function handleSocketData (data) {
if (!data) {
return
}
switch (+data.eventType) {
case 3: // 设备调试返回结果
socketBus.$emit(debugEvent, data) //子组件向父组件传递debugEvent事件和data数据
break;
}
}
3.4、暴露定义的变量,以便父组件引用使用
export { useSocket, socketUrl, socketBus }
4、组件product.vue中使用websocket事件
import { socketBus, debugEvent } from '@/modules/websocket'
mounted () {
socketBus.$on(debugEvent, this.dealResult) //sockeBus绑定debugEvent事件
},
beforeDestroy () {
socketBus.$off(debugEvent) //sockeBus解绑debugEvent事件
}