1. 在utils下新建websocket.js文件

// import { showinfomsg, showerrormsg } from '@/utils/popinfo'
import elementui from 'element-ui';
function initwebsocket(e) {
    console.log(e)
    const wsuri = ws_api + "/websocket/" + e;
    this.socket = new websocket(wsuri)//这里面的this都指向vue
    this.socket.onerror = websocketonerror;
    this.socket.onmessage = websocketonmessage;
    this.socket.onclose = closewebsocket;
}
function websocketonerror(e) {
    elementui.notification({
        title: '',
        message: "websocket连接发生错误" + e,
        type: 'error',
        duration: 0,
    });
}
function websocketonmessage(e) {
    const data = json.parse(e.data);
    console.log(data.msgtype === "info", data.msgtype === "info")
    if (data.msgtype === "info") {
        elementui.notification({
            title: '',
            message: data.msg,
            type: 'success',
            duration: 3000,
        });

    } else if (data.msgtype === "error") {
        elementui.notification({
            title: '',
            message: data.msg,
            type: 'error',
            duration: 0,
        });
    }
}
// 关闭websiocket
function closewebsocket() {
    console.log('连接已关闭...')
}
function close() {
    this.socket.close() // 关闭 websocket
    this.socket.onclose = function (e) {
        console.log(e)//监听关闭事件
        console.log('关闭')
    }
}
function websocketsend(agentdata) {
    this.socket.send(agentdata);
}
export default {
    initwebsocket, close
}

如果想刷新重新链接websocket 可以在app.vue页面里添加个钩子函数

 mounted() {
    //当在任一路由页面被刷新时,便是根组件app被从新建立,此时能够进行websocket重连
    //从localstorage中获取用户信息,是登陆状态则能够进行websocket重连
    let token = localstorage.getitem("token");
    if (token) {
      // usermessage = json.parse(usermessage);
      this.$websocket.initwebsocket(token);
    }
  },

客户端主动关闭websocket 在关闭的地方触发函数就可以

 logout() {
      // localstorage.clear();
      localstorage.removeitem("token");
      this.$websocket.close();
      this.$store.dispatch("logout").then(() => {
        location.reload();
      });
    },

注:$websocket 是在main.js中全局注册了websocket.js文件

到此这篇关于vue 项目中使用websocket的文章就介绍到这了,更多相关vue使用websocket内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!