关键词搜索

源码搜索 ×
×

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

发布2021-05-11浏览1892次

详情内容

运行结果如下:

程序结构如下:

关键代码:

App.vue

  1. <template>
  2. <a-layout class="layout">
  3. <a-layout-header>
  4. <a-menu
  5. theme="dark"
  6. mode="horizontal"
  7. v-model:selectedKeys="selectedKeys"
  8. :style="{ lineHeight: '64px' }"
  9. >
  10. <a-menu-item key="title">Ant Design Vue WebService实例</a-menu-item>
  11. </a-menu>
  12. </a-layout-header>
  13. <br/>
  14. <a-layout-content style="padding: 0 50px">
  15. <SendMsg></SendMsg>
  16. </a-layout-content>
  17. <a-layout-footer style="text-align: center">
  18. Footer
  19. </a-layout-footer>
  20. </a-layout>
  21. </template>
  22. <script>
  23. import {defineComponent} from 'vue'
  24. import SendMsg from './components/SendMsg'
  25. export default defineComponent({
  26. name: 'app',
  27. components: {
  28. SendMsg
  29. }
  30. });
  31. </script>
  32. <style>
  33. .site-layout-content {
  34. min-height: 280px;
  35. padding: 24px;
  36. background: #fff;
  37. }
  38. #components-layout-demo-top .logo {
  39. float: left;
  40. width: 120px;
  41. height: 31px;
  42. margin: 16px 24px 16px 0;
  43. background: rgba(255, 255, 255, 0.3);
  44. }
  45. .ant-row-rtl #components-layout-demo-top .logo {
  46. float: right;
  47. margin: 16px 0 16px 24px;
  48. }
  49. [data-theme='dark'] .site-layout-content {
  50. background: #141414;
  51. }
  52. </style>

SendMsg.vue

  1. <template>
  2. <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
  3. <a-form-item label="消息" v-bind="validateInfos['msg.content']">
  4. <a-input v-model:value="modelRef.msg.content" />
  5. </a-form-item>
  6. <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
  7. <a-button type="primary" @click.prevent="onSubmit">发送</a-button>
  8. <a-button style="margin-left: 10px" @click="reset">重置</a-button>
  9. </a-form-item>
  10. </a-form>
  11. </template>
  12. <script lang="ts">
  13. import { defineComponent, reactive, onMounted } from 'vue';
  14. import { useForm } from '@ant-design-vue/use';
  15. import { notification } from 'ant-design-vue';
  16. import axios from 'axios';
  17. export default defineComponent({
  18. name: 'SendMsg',
  19. setup() {
  20. let websocket;
  21. let token;
  22. const modelRef = reactive({
  23. msg: {
  24. content: '',
  25. }
  26. });
  27. const { resetFields, validateInfos } = useForm(
  28. modelRef,
  29. reactive({
  30. name: [
  31. {
  32. required: true,
  33. message: 'Please input name',
  34. },
  35. ],
  36. 'msg.content': [
  37. {
  38. required: true,
  39. message: 'Please input sub name',
  40. },
  41. ],
  42. }),
  43. );
  44. const onSubmit = () => {
  45. axios.post('/msg', {
  46. msg: modelRef.msg.content
  47. })
  48. .then(function (response) {
  49. console.log(response);
  50. })
  51. .catch(function (error) {
  52. console.log(error);
  53. });
  54. };
  55. const reset = () => {
  56. resetFields();
  57. };
  58. const onOpen = () => {
  59. console.log('WebSocket连接成功,状态码:', websocket.readyState)
  60. };
  61. const onMessage = (event) => {
  62. console.log('WebSocket收到消息:', event.data);
  63. notification['info']({
  64. message: '收到消息',
  65. description: event.data,
  66. });
  67. };
  68. const onError = () => {
  69. console.log('WebSocket连接错误,状态码:', websocket.readyState)
  70. };
  71. const onClose = () => {
  72. console.log('WebSocket连接关闭,状态码:', websocket.readyState)
  73. };
  74. const initWebSocket = () => {
  75. // 连接成功
  76. websocket.onopen = onOpen;
  77. // 收到消息的回调
  78. websocket.onmessage = onMessage;
  79. // 连接错误
  80. websocket.onerror = onError;
  81. // 连接关闭的回调
  82. websocket.onclose = onClose;
  83. };
  84. onMounted(() => {
  85. // WebSocket
  86. if ('WebSocket' in window) {
  87. token = Math.floor(Math.random() * 100000) + 1;
  88. // 连接地址:ws://127.0.0.1:8880/ws/xxx
  89. websocket = new WebSocket(process.env.VUE_APP_WS_SERVER + '/ws/' + token);
  90. initWebSocket()
  91. // 关闭
  92. // websocket.close();
  93. } else {
  94. alert('当前浏览器 不支持')
  95. }
  96. });
  97. return {
  98. labelCol: { span: 4 },
  99. wrapperCol: { span: 14 },
  100. validateInfos,
  101. reset,
  102. modelRef,
  103. onSubmit,
  104. };
  105. },
  106. });
  107. </script>

main.js

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import Antd from 'ant-design-vue';
  4. import 'ant-design-vue/dist/antd.css';
  5. import axios from 'axios';
  6. axios.defaults.baseURL = process.env.VUE_APP_SERVER;
  7. const app = createApp(App);
  8. app.use(Antd).mount('#app');

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载