首页 > 技术文章 > vue创建公共函数工具utils文件

qianxiaoPro 2021-04-30 15:10 原文

说明: 封装一个公共方法connectWebsocket() ,进行全局调用

1、在src下创建utils文件夹,目录下创建index.html

import config from '@/config'
export default {
  // websocket
  websocket: '',
  // 创建websocket链接
  connectWebsocket (val) {
    debugger
    let _this = this
    const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
    if (typeof (WebSocket) === 'undefined') {
      alert('您的浏览器不支持socket')
    } else {
      // 实例化websocket
      var path = baseUrl.replace('http', 'ws') + '/websocket/' + val
      _this.websocket = ''
      _this.websocket = new WebSocket(path)
      // 监听websocket连接
      _this.websocket.onopen = function (event) {
        console.log('建立连接')
        sessionStorage.setItem('ws', _this.websocket)
      }
      // 监听websocket错误信息
      _this.websocket.onerror = function () {
        alert('websocket通信发生错误!')
      }
      // websocket
      _this.websocket.onmessage = function (event) {
        debugger
        var t
        if (event.data) {
          try {
            // 封装返回的数据
            t = JSON.parse(event.data)
            console.log(t.content)
          } catch (e) {
            // 如果是字符串则直接赋值
            t = event.data
          }
        }
        // 如果是登陆
        if (t === 'uccessfulconnection') {
          // 音乐播放欢迎登陆
        } else { // 发送消息
          if (t instanceof Object) {
            if (t.type === 0) {
              // 发送的消息
              Notice.info({
                title: '消息通知',
                desc: t.username + t.content
              })
              Header.methods.changeunreadcount('add', 1)
            } else if (t.type === 1) {
              // 发送的公告
              Notice.info({
                title: '公告通知',
                desc: t.username + t.content
              })
            } else {
            }
          } else if (t instanceof String) {
            // 分配任务时工作流调用
          } else {
            // 其他
          }
          // 弹窗提醒, 播放音乐
          // document.getElementById('notice').play();
          //   }
        }
      }
      // websocket
      _this.websocket.onclose = function (event) {
        console.log('连接关闭')
        _this.websocket = ''
        sessionStorage.removeItem('ws')
      }
      // 页面刷新时关闭连接(此处不写一样会关闭,因一些原因要写上)
      window.onbeforeunload = function () {
        _this.websocket.close()
        _this.websocket = ''
        sessionStorage.removeItem('ws')
      }
    }
  }
}

2、封装使用,在main.js中添加

// 工具函数引入
import Utils from './utils'
 
Object.defineProperty(Vue.prototype, '$Utils', {value: Utils})

3、调用函数

this.$Utils.connectWebsocket(res.id)

 

推荐阅读