码迷,mamicode.com
首页 > Web开发 > 详细

websocket在vue中使用

时间:2019-12-26 11:29:58      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:sock   set   引入   console   received   current   ons   路由   创建文件   

方法一.组件中单独使用

 1.在methods中   
WebSocketSet(){
       if (WebSocket in window){
         this.ws = new WebSocket(`${axios.defaults.baseURL9}`);  
           this.ws.onmessage =  (res=>{
             let   received_msg= JSON.parse(res.data);
                 console.log("数据已接收...",received_msg);
                 this.newsList=received_msg;
           }) 
           this.ws.onopen=(res=>{
              console.log("socket连接成功")
               this.ws.send(this.currentId);
           })
          
         //......此处省略ws其他属性操作
          }else{
            alert(当前浏览器 Not support websocket)
          }  
    },
2.在destroyed中关闭websocket
 destroyed(){
      this.ws.close();//离开路由之后断开websocket连接
    }

方法二.封装公共方法

1.在src下创建文件夹存放websocket.js(soketLink中为请求服务)
import wesk from "./soketLink"
class socket{
  constructor(){
    this.ws=null
  }
  WebSocketSet(par, Callback) {
    if (WebSocket in window) {
       this.ws=wesk.wesk()
    //  var ws = new WebSocket(`${axios.defaults.baseURL9}`);   
      this.ws.onopen = (res => {
        console.log("socket连接成功")
        this.ws.send(par);
      })
      this.ws.onmessage = (res => {
        let received_msg = JSON.parse(res.data);
        console.log("数据已接收...", received_msg);
        // this.newsList=received_msg;
        Callback(received_msg)
      })

    } else {
      alert(当前浏览器 Not support websocket)
    }
  }
  close(){
    this.ws.close()
    this.ws.onclose = (res => {
      console.log(console.log("socket已经关闭"))
    })
  }

}
export default socket
2.在组件中引入websocket.js
import socket from "../../../resource/websocket.js"

data中定义websocket:null,

mounted() {
    this.websocket=new socket()    
 this.websocket.WebSocketSet(this.currentId,this.getSocketdata);      
  },

methods中接收数据
  //websocket返回数据
getSocketdata(res){
         console.log(res,997788)
         this.newsList=res
      },


 destroyed(){
      //离开路由之后断开websocket连接
     this.websocket.close() 
    }

websocket在vue中使用

标签:sock   set   引入   console   received   current   ons   路由   创建文件   

原文地址:https://www.cnblogs.com/crazy-girl/p/12100976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!