webScoket实时通讯聊天

<template>
  <view>
    <view v-for="(msg, index) in messages" :key="index">
      {
  { msg }}
    </view>
    <input v-model="inputMsg" type="text" placeholder="请输入消息" @confirm="sendMessage" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      inputMsg: '',
      messages: []
    };
  },
  onLoad() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      this.socket = new WebSocket('ws://your_websocket_server_url');
      
      this.socket.onopen = () => {
        console.log('WebSocket连接已打开');
      };
      
      this.socket.onmessage = (event) => {
        this.messages.push(event.data);
      };
      
      this.socket.onerror = (event) => {
        console.error('WebSocket连接发生错误:', event);
      };
      
      this.socket.onclose = () => {
        console.log('WebSocket连接已关闭');
      };
    },
    sendMessage() {
      if (this.inputMsg.trim() !== '') {
        this.socket.send(this.inputMsg);
        this.inputMsg = '';
      }
    }
  }
};
</script>
  1. App.vue中添加路由配置:
    <template>
      <view>
        <router-view />
      </view>
    </template>
    
    <script>
    export default {};
    </script>
    

  2. main.js中配置全局引入的WebSocket库(如果有的话):
    import Vue from 'vue';
    import App from './App';
    Vue.config.productionTip = false;
    App.mpType = 'app';
    const app = new Vue({
      ...App
    });
    app.$mount();
    

相关推荐

  1. webScoket实时通讯聊天

    2024-02-21 13:06:01       59 阅读
  2. netty+websocket实现简易聊天

    2024-02-21 13:06:01       33 阅读
  3. fastapi实现websocket在线聊天

    2024-02-21 13:06:01       65 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-21 13:06:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-21 13:06:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-21 13:06:01       87 阅读
  4. Python语言-面向对象

    2024-02-21 13:06:01       96 阅读

热门阅读

  1. CSS的全局值 initial inherit revert overlay unset

    2024-02-21 13:06:01       49 阅读
  2. MFC中不同编码格式内容的写入

    2024-02-21 13:06:01       48 阅读
  3. 手写table表格(一表头多数据)

    2024-02-21 13:06:01       51 阅读
  4. C/C++三角函数math.h库详解

    2024-02-21 13:06:01       49 阅读
  5. ThreadLocal(4):ThreadLocal的核心方法源码

    2024-02-21 13:06:01       49 阅读
  6. 代码随想录算法训练营第三八天 | 动态规划

    2024-02-21 13:06:01       63 阅读
  7. 基于STM32的家庭温湿度控制系统的设计

    2024-02-21 13:06:01       44 阅读