data(){
retuen {
ws: null,
}
}
mounted() {
// 看需求决定在哪里开启webSocket,这里放在dom挂载后
this.initWebSocket()
},
methods: {
// 建立链接
initWebSocket() {
//socket内不能使用this, 这里改为_this
let _this = this;
// _this.params(所需传参id)
// `ws://192.168.0.ip:6011/socket/${_this.params}`: 后端给的接口
_this.ws = new WebSocket(`ws://192.168.0.ip:6011/socket/${_this.params}`);
_this.ws.addEventListener("open", function (e) {
console.log("链接成功!");
});
_this.ws.onopen = function () {
console.log("链接成功!");
// ws.send(sessionStorage.getItem('key'))
};
_this.ws.onerror = function () {
console.log("连接错误!");
};
_this.ws.onclose = fun
websocket实时通讯(vue2)
于 2023-07-20 14:02:24 首次发布