websocket在vue中的使用
时间: 2024-02-09 16:40:30 浏览: 167
1. 安装websocket库
```bash
npm install --save vue-native-websocket
```
2. 在Vue中引入WebSocket
```javascript
import VueNativeSock from 'vue-native-websocket'
Vue.use(VueNativeSock, 'ws://localhost:8080', {
reconnection: true, //是否自动重连
reconnectionAttempts: 5, //重连次数
reconnectionDelay: 3000, //重连时间间隔,单位:毫秒
store: store, //Vuex Store实例
format: 'json' //接收/发送数据的格式,可选值:'json'或'blob'
})
```
3. 在Vue组件中使用WebSocket
```javascript
export default {
mounted () {
this.$connect() //建立连接
},
methods: {
sendMessage () {
this.$socket.send('Hello WebSocket') //发送消息
}
}
}
```
4. 在Vue组件中监听WebSocket事件
```javascript
export default {
mounted () {
this.$connect() //建立连接
this.$on('message', (msg) => {
console.log(msg) //接收到消息
})
},
methods: {
sendMessage () {
this.$socket.send('Hello WebSocket') //发送消息
}
}
}
```
阅读全文