1 下载vue socket
npm i vue-socket.io -S
2 mian.js页面引入
// socket 即时通讯
//main.js
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
// debug: true,
connection: 'http://xxxx:xxxx', //连接的静态地址
}))
3 页面使用与 位置created平级 监听new_msg返回的数据
sockets:{
//连接成功
connect: function () {
console.log('socket connected')
},
customEmit: function (data) {
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')},
//断开重连 在此位置会进行多次的重新连接 直到连接成功
reconnect(data){
this.$socket.emit('connect',1)
},
//连接断开 在此位置会进行多次的重新连接 直到连接成功
reconnect(data){
this.$socket.emit('reconnect','')
},
//new_msg后台定义的事件监听 打印返回数据
new_msg(data){
this.alertNumber=JSON.parse(data)
},
},
4如果要发送事件 login 是与后端约定的方法,然后user_info.role_id是都断要的id
this.$socket.emit('login', user_info.role_id); //参数:('连接的事件','传给后台的值')