前段时间公司项目要用到socket实现推送功能,接到的任务就是使用vue-socket.io,这.....当时作为socket小白的我,就这么翻呀翻它的文档,搞了许久,效果不理想(当时的我不能实现组件内new......)
辗转了几天,实在无果,看看了他的封装,也是基于socket.io-client,那我为啥不直接用socket.io-client来实现哩,不多说,直接上代码,记录下socketio的初次学习
// .vue
import SocketIO from "socket.io-client";
import axios from "@/router/axios";
data() {
return {
socket: null
}
},
mounted() {
this.newSocket()
},
beforeDestroy() {
this.socket && this.socket.ondisconnect()
},
methods: {
async newSocket () {
const token = this.access_token
const res = await axios ( {
method: "get",
url: "/socket/socket/ws",
headers: {'X-Requested-With': 'XMLHttpRequest',
'Authorization': 'Bearer ' + token
},
})
this.socket = SocketIO(res.data.data.url,{transports:['websocket','xhr-polling','jsonp-polling']})
this.socket.on('connect', () => {
console.log('连接成功')
})
this.socket.on('response', (res) => {
this.$message.success(res.msg)
})
this.socket.on('chat_message', (msg) => {
this.messages.push(msg)
})
this.socket.on('broadcast', (data) => {
let res = this.$refs.audio.play()
const h = this.$createElement;
this.$notify({
title: '新消息',
duration:0,
message: h('i', { style: 'color: teal'}, data.message)
})
})
this.socket.on('disconnect', () => {
console.log('断开连接')
})
},
}