在vue中使用原生websocket连接失败
<template>
<button @click="websocketonmessage()">查看</button>
</template>
<script>
export default {
data () {
return {
websock:null
};
},
methods: {
// webscoket实现长连接
initWebSocket(){
//初始化websocket
const wsurl = "我的地址";
this.websock = new WebSocket(wsurl);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websocket = this.websocket;
this.websock.onclose = this.websocketclose;
},
websocket(){
this.initWebSocket();
},
websocketonopen(e){
console.log("WebSocket连接成功",e);
},
websocketonerror(e) { //错误
console.log("连接错误",e);
},
websocketonmessage(res){
console.log("数据",res.data);
},
websocketclose(e){
console.log('断开连接',e)
},
},
created () {
this.initWebSocket();
},
destroyed(){
this.websocketclose();
}
}
</script>
是没配置hosts的原因,已解决!