vue实现socket连接
Vue 中实现 Socket 连接
使用原生 WebSocket
在 Vue 项目中可以直接使用浏览器原生 WebSocket API 实现连接。创建一个 WebSocket 实例并监听事件即可完成基本通信。
// 在 Vue 组件中
export default {
data() {
return {
socket: null,
messages: []
}
},
mounted() {
this.initWebSocket()
},
methods: {
initWebSocket() {
this.socket = new WebSocket('ws://your-socket-server-url')
this.socket.onopen = () => {
console.log('WebSocket connected')
}
this.socket.onmessage = (event) => {
this.messages.push(event.data)
}
this.socket.onerror = (error) => {
console.error('WebSocket error:', error)
}
this.socket.onclose = () => {
console.log('WebSocket disconnected')
}
},
sendMessage(message) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message)
}
}
},
beforeDestroy() {
this.socket.close()
}
}
使用 Socket.IO 客户端
对于需要更高级功能的场景,Socket.IO 是更流行的选择。需要先安装 socket.io-client 库。
npm install socket.io-client
在 Vue 组件中使用:

import io from 'socket.io-client'
export default {
data() {
return {
socket: null,
messages: []
}
},
mounted() {
this.initSocket()
},
methods: {
initSocket() {
this.socket = io('http://your-socket-server-url')
this.socket.on('connect', () => {
console.log('Socket.IO connected')
})
this.socket.on('message', (data) => {
this.messages.push(data)
})
this.socket.on('disconnect', () => {
console.log('Socket.IO disconnected')
})
},
emitMessage(message) {
this.socket.emit('send-message', message)
}
},
beforeDestroy() {
if (this.socket) {
this.socket.disconnect()
}
}
}
封装为 Vue 插件
对于大型项目,可以将 Socket 逻辑封装为 Vue 插件实现全局管理。
// socket-plugin.js
import io from 'socket.io-client'
export default {
install(Vue, options) {
const socket = io(options.connection)
Vue.prototype.$socket = socket
Vue.mixin({
beforeDestroy() {
if (this.$options.socket) {
this.$socket.off(this.$options.socket)
}
}
})
}
}
在 main.js 中使用插件:

import Vue from 'vue'
import SocketPlugin from './socket-plugin'
Vue.use(SocketPlugin, {
connection: 'http://your-socket-server-url'
})
在组件中监听事件:
export default {
socket: {
message(data) {
console.log('Received message:', data)
}
}
}
注意事项
WebSocket 连接需要考虑跨域问题,确保服务器配置了正确的 CORS 策略。对于生产环境,建议使用 wss:// 协议确保通信安全。
重连逻辑是 Socket 通信中的重要环节,Socket.IO 默认实现了自动重连,而原生 WebSocket 需要手动实现。根据项目需求选择合适的方案。






