目录形貌项目需求是做一个全局谈天系统,随时担当新消息关照,实时更新谈天内容 方式就是做一个全局的ws属性,统一发送,统一担当,利用xuex存储需要的数据 代码步骤第一步utils下新建globalWs.js, 用来处理全部的ws事件, 代码如下: [code]//utils/globalWs.js import { Notification } from 'element-ui' //引入ui组件, 作消息关照 import router from '@/router/routers' //引入router, 作页面跳转 import store from '@/store' //引入store, 作谈天消息存储 export default { ws: {}, //发送ws方法 sendWs: function(data) { console.log(data, '发送的消息') this.ws.send(JSON.stringify(data)) }, //初始化ws initWs: function() { const that = this if ('WebSocket' in window) { // 打开一个 web socket const ws = new WebSocket(process.env.VUE_APP_WS_API) that.ws = ws ws.onopen = function() { console.log('ws.onopen') // Web Socket 已连接上,利用 that.sendWs() 方法发送数据, 例如 that.sendWs({name:'张三'}) } ws.onmessage = function(evt) { console.log('全局数据已接收...', evt.data) var receivedData = JSON.parse(evt.data) // 添加谈天记载代码 // store.commit('ADD_CALL_LOG', data) //新消息关照 //Notification.info({ // title: '消息', // message: '您有一条新的消息', // onClick: () => { // if (router.currentRoute.fullPath != '/airobot/chat') { // 页面跳转 // router.push('/airobot/chat') // } // } //}) } } // 非常断开重连(2023.4.12更新) ws.onerror = function(err) { console.log('websocket 断开: ' + err, ws.readyState) if (ws.readyState != 0) { setTimeout(() => { that.initWs() }, 1000) } } }, //断开socked方法 closeWs: function() { // 关闭定时器 console.log('关闭定时器') clearInterval(this.heartbeat) console.log('关闭ws') this.ws.close() } }[/code]第二步main.js中注册全局属性 [code]//main.js import globalWs from './utils/globalWs.js' Vue.prototype.$globalWs = globalWs[/code]优雅之处解说可以在任何时刻去选择初始化ws, 可以是app.vue中, 也可以是验证完用户信息后 可以随时利用globalWs.send()发送谈天消息
总结以上为个人经验,渴望能给大家一个参考,也渴望大家多多支持脚本之家。 来源:https://www.jb51.net/javascript/326680vlo.htm 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
|手机版|小黑屋|梦想之都-俊月星空
( 粤ICP备18056059号 )|网站地图
GMT+8, 2025-7-2 09:07 , Processed in 0.029521 second(s), 18 queries .
Powered by Mxzdjyxk! X3.5
© 2001-2025 Discuz! Team.