vue代码
<template>
<div>
<div style="display: flex;justify-content: center;align-items: center;">
<button @click="btnClick">发送</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
ws: null,
WebSocketUrl: 'ws://localhost:7777/websocket/1',
}
},
created() {
this.handleConnect()
},
destroyed() {
this.handleExit()
},
methods: {
handleConnect() {
this.ws = new WebSocket(this.WebSocketUrl)
this.ws.onmessage = (e) => {
console.log(e)
}
this.ws.onclose = () => {
console.log('连接关闭')
}
},
handleExit() {
if (this.ws) {
this.ws.close()
this.ws = null
}
},
btnClick() {
this.ws.send('test')
},
}
}
</script>
<style scoped></style>
...小于 1 分钟