Vue笔记-Ant Design Vue构建前端连接后端WebSocket

Posted IT1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue笔记-Ant Design Vue构建前端连接后端WebSocket相关的知识,希望对你有一定的参考价值。

运行结果如下:

程序结构如下:

关键代码:

App.vue

<template>
  <a-layout class="layout">
    <a-layout-header>
      <a-menu
              theme="dark"
              mode="horizontal"
              v-model:selectedKeys="selectedKeys"
              :style="{ lineHeight: '64px' }"
      >
        <a-menu-item key="title">Ant Design Vue WebService实例</a-menu-item>
      </a-menu>
    </a-layout-header>
    <br/>
    <a-layout-content style="padding: 0 50px">
      <SendMsg></SendMsg>
    </a-layout-content>
    <a-layout-footer style="text-align: center">
      Footer
    </a-layout-footer>
  </a-layout>
</template>

<script>

  import {defineComponent} from 'vue'
  import SendMsg from './components/SendMsg'
  export default defineComponent({
    name: 'app',
    components: {
      SendMsg
    }
  });
</script>

<style>
  .site-layout-content {
    min-height: 280px;
    padding: 24px;
    background: #fff;
  }
  #components-layout-demo-top .logo {
    float: left;
    width: 120px;
    height: 31px;
    margin: 16px 24px 16px 0;
    background: rgba(255, 255, 255, 0.3);
  }
  .ant-row-rtl #components-layout-demo-top .logo {
    float: right;
    margin: 16px 0 16px 24px;
  }

  [data-theme='dark'] .site-layout-content {
    background: #141414;
  }
</style>

SendMsg.vue

<template>
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="消息" v-bind="validateInfos['msg.content']">
            <a-input v-model:value="modelRef.msg.content" />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click.prevent="onSubmit">发送</a-button>
            <a-button style="margin-left: 10px" @click="reset">重置</a-button>
        </a-form-item>
    </a-form>
</template>

<script lang="ts">
    import { defineComponent, reactive, onMounted } from 'vue';
    import { useForm } from '@ant-design-vue/use';
    import { notification } from 'ant-design-vue';
    import axios from 'axios';
    export default defineComponent({

        name: 'SendMsg',
        setup() {
            let websocket;
            let token;
            const modelRef = reactive({
                msg: {
                    content: '',
                }
            });
            const { resetFields, validateInfos } = useForm(
                modelRef,
                reactive({
                    name: [
                        {
                            required: true,
                            message: 'Please input name',
                        },
                    ],
                    'msg.content': [
                        {
                            required: true,
                            message: 'Please input sub name',
                        },
                    ],
                }),
            );
            const onSubmit = () => {

                axios.post('/msg', {
                    msg: modelRef.msg.content
                })
                    .then(function (response) {
                        console.log(response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            };
            const reset = () => {
                resetFields();
            };

            const onOpen = () => {
                console.log('WebSocket连接成功,状态码:', websocket.readyState)
            };
            const onMessage = (event) => {
                console.log('WebSocket收到消息:', event.data);
                notification['info']({
                    message: '收到消息',
                    description: event.data,
                });
            };
            const onError = () => {
                console.log('WebSocket连接错误,状态码:', websocket.readyState)
            };
            const onClose = () => {
                console.log('WebSocket连接关闭,状态码:', websocket.readyState)
            };
            const initWebSocket = () => {
                // 连接成功
                websocket.onopen = onOpen;
                // 收到消息的回调
                websocket.onmessage = onMessage;
                // 连接错误
                websocket.onerror = onError;
                // 连接关闭的回调
                websocket.onclose = onClose;
            };

            onMounted(() => {
                // WebSocket
                if ('WebSocket' in window) {
                    token = Math.floor(Math.random() * 100000) + 1;
                    // 连接地址:ws://127.0.0.1:8880/ws/xxx
                    websocket = new WebSocket(process.env.VUE_APP_WS_SERVER + '/ws/' + token);
                    initWebSocket()

                    // 关闭
                    // websocket.close();
                } else {
                    alert('当前浏览器 不支持')
                }
            });

            return {
                labelCol: { span: 4 },
                wrapperCol: { span: 14 },
                validateInfos,
                reset,
                modelRef,
                onSubmit,
            };
        },
    });
</script>

main.js

import { createApp } from 'vue'
import App from './App.vue'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import axios from 'axios';

axios.defaults.baseURL = process.env.VUE_APP_SERVER;

const app = createApp(App);
app.use(Antd).mount('#app');

 

 

以上是关于Vue笔记-Ant Design Vue构建前端连接后端WebSocket的主要内容,如果未能解决你的问题,请参考以下文章

Ant Design of Vue @1.7.8 学习笔记(Vue2版本)

Vue开发者的福音:antd design官方正式发布ant-design-vue

Vue.js高效前端开发 • Ant Design of Vue框架基础

Vue.js高效前端开发 • Ant Design of Vue框架基础

Vue.js高效前端开发 • Ant Design of Vue框架进阶

Vue.js高效前端开发 • Ant Design of Vue框架进阶