跳至主要內容

vue2使用websocket

荒芜...小于 1 分钟前端vue2websocket

vue2使用websocket

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>

点击发送

界面
界面

后端日志

后端日志
后端日志
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.2.0