uniapp 封装websocket 全局引用
时间: 2023-10-31 09:04:37 浏览: 153
在uniapp中封装websocket并实现全局引用,可以按照以下步骤进行:
1. 在uniapp项目的common目录下创建一个websocket.js文件,用于封装websocket:
```javascript
export default {
socket: null,
init(url) {
this.socket = new WebSocket(url);
this.socket.onopen = this.onopen;
this.socket.onmessage = this.onmessage;
this.socket.onclose = this.onclose;
this.socket.onerror = this.onerror;
},
onopen() {
console.log("websocket连接成功");
},
onmessage(event) {
console.log("收到消息:", event.data);
},
onclose() {
console.log("websocket连接关闭");
},
onerror() {
console.log("websocket连接错误");
},
send(data) {
if (this.socket && this.socket.readyState === 1) {
this.socket.send(data);
}
},
close() {
if (this.socket) {
this.socket.close();
}
}
};
```
2. 在uniapp项目的main.js文件中全局引用websocket.js:
```javascript
import websocket from "@/common/websocket.js";
Vue.prototype.$websocket = websocket;
```
3. 在需要使用websocket的页面中,先通过this.$websocket.init(url)方法初始化websocket连接,然后即可使用this.$websocket.send(data)方法发送消息,收到消息后会自动触发this.$websocket.onmessage回调函数。
```javascript
export default {
mounted() {
this.$websocket.init("ws://localhost:8080");
},
methods: {
sendMessage() {
this.$websocket.send("hello world");
}
}
};
```
阅读全文
相关推荐
















