Vue2聊天组件vue-beautiful-chat

该文介绍了如何在Vue.js项目中安装和配置vue-beautiful-chat插件,包括引入组件、设置属性以及与socket.io服务器进行交互,实现一个包含发送、接收消息功能的聊天窗口。同时,展示了处理用户输入和显示消息列表的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装

npm i vue-beautiful-chat

2.main.js中引入

import Chat from 'vue-beautiful-chat'
Vue.use(Chat)

 3.对接接口的完整代码(复制过去就可以用)

<template>
  <div>
    <beautiful-chat
      :participants="participants"
      :titleImageUrl="titleImageUrl"
      :onMessageWasSent="onMessageWasSent"
      :messageList="messageList"
      :newMessagesCount="newMessagesCount"
      :isOpen="isChatOpen"
      :close="closeChat"
      :icons="icons"
      :open="openChat"
      :showEmoji="true"
      :showFile="true"
      :showEdition="true"
      :showDeletion="true"
      :showTypingIndicator="showTypingIndicator"
      :showLauncher="true"
      :showCloseButton="true"
      :colors="colors"
      :alwaysScrollToBottom="alwaysScrollToBottom"
      :messageStyling="messageStyling"
      @onType="handleOnType"
      @edit="editMessage"
    />
  </div>
</template>
<script>
import CloseIcon from "@/assets/logo.png";
import OpenIcon from "@/assets/logo.png";
import FileIcon from "@/assets/logo.png";
import CloseIconSvg from "@/assets/logo.png";
import io from "socket.io-client";
export default {
  name: "app",
  data() {
    return {
      // 创建一个 socket 对象
      socket: null,
      icons: {
        open: {
          img: OpenIcon,
          name: "default",
        },
        close: {
          img: CloseIcon,
          name: "default",
        },
        file: {
          img: FileIcon,
          name: "default",
        },
        closeSvg: {
          img: CloseIconSvg,
          name: "default",
        },
      },
      participants: [
        {
          id: "user1",
          name: "Matteo",
          imageUrl:
            "https://avatars3.githubusercontent.com/u/1915989?s=230&v=4",
        },
        {
          id: "user2",
          name: "Support",
          imageUrl:
            "https://avatars3.githubusercontent.com/u/37018832?s=200&v=4",
        },
      ], // the list of all the participant of the conversation. `name` is the user name, `id` is used to establish the author of a message, `imageUrl` is supposed to be the user avatar.
      titleImageUrl:
        "https://a.slack-edge.com/66f9/img/avatars-teams/ava_0001-34.png",
      messageList: [
        { type: "text", author: `me`, data: { text: `Say yes!` } },
        { type: "text", author: `user1`, data: { text: `No.` } },
      ], // the list of the messages to show, can be paginated and adjusted dynamically
      newMessagesCount: 0,
      isChatOpen: false, // to determine whether the chat window should be open or closed
      showTypingIndicator: "", // when set to a value matching the participant.id it shows the typing indicator for the specific user
      colors: {
        header: {
          bg: "#4e8cff",
          text: "#ffffff",
        },
        launcher: {
          bg: "#4e8cff",
        },
        messageList: {
          bg: "#ffffff",
        },
        sentMessage: {
          bg: "#4e8cff",
          text: "#ffffff",
        },
        receivedMessage: {
          bg: "#eaeaea",
          text: "#222222",
        },
        userInput: {
          bg: "#f4f7f9",
          text: "#565867",
        },
      }, // specifies the color scheme for the component
      alwaysScrollToBottom: false, // when set to true always scrolls the chat to the bottom when new events are in (new message, user starts typing...)
      messageStyling: true, // enables *bold* /emph/ _underline_ and such (more info at github.com/mattezza/msgdown)
    };
  },
  created() {
    // 建立服务器的连接
    console.log("连接");
    this.socket = io("http://toutiao.itheima.net", {
      query: {
        token: "8d6b045d-a15f-4d4a-9841-340ddf27a283",
      },
      transports: ["websocket"],
    });
    console.log("socket", this.socket);
    // 收消息
    this.socket.on("message", (data) => {
      console.log("收到消息", data);
      // 将内容添加到聊天列表中
      const item = {
        type: "text",
        author: `user1`,
        data: { text: `${data.msg}` },
      };
      this.messageList.push(item);
      // this.chatList.push({
      //   isme: false,
      //   t: data.msg,
      // });
      // 自动滚动到底部
      // this.$nextTick(() => {
      //   // 滚动到最后面
      //   this.$refs.chat.scrollTop = this.$refs.chat.scrollHeight;
      // });
    });
  },
  methods: {
    sendMessage(text) {
      if (text.length > 0) {
        this.newMessagesCount = this.isChatOpen
          ? this.newMessagesCount
          : this.newMessagesCount + 1;
        this.onMessageWasSent({
          author: "support",
          type: "text",
          data: { text },
        });
      }
    },
    // 发送消息
    onMessageWasSent(message) {
      // called when the user sends a message
      console.log("限制性这个", message);
      this.messageList = [...this.messageList, message];
      // 将消息发送到服务器
      this.socket.emit("message", {
        msg: message.data.text,
        timestamp: Date.now(),
      });
      console.log("发送到服务器");
    },
    openChat() {
      // called when the user clicks on the fab button to open the chat
      this.isChatOpen = true;
      this.newMessagesCount = 0;
    },
    closeChat() {
      // called when the user clicks on the botton to close the chat
      this.isChatOpen = false;
    },
    handleScrollToTop() {
      // called when the user scrolls message list to top
      // leverage pagination for loading another page of messages
    },
    handleOnType() {
      console.log("Emit typing event");
    },
    editMessage(message) {
      const m = this.messageList.find((m) => m.id === message.id);
      m.isEdited = true;
      m.data.text = message.data.text;
    },
  },
};
</script>

 

好的,让我们来看一下如何使用vue-beautiful-chat这个聊天组件。 首先,安装vue-beautiful-chat组件: ```bash npm install vue-beautiful-chat --save ``` 然后在你的Vue组件中引入并注册vue-beautiful-chat组件: ```javascript <template> <div> <beautiful-chat :messages="messages" @send="onSend"></beautiful-chat> </div> </template> <script> import { BeautifulChat } from 'vue-beautiful-chat' export default { name: 'MyChatComponent', components: { BeautifulChat }, data() { return { messages: [] } }, methods: { onSend(text) { // 处理发送的消息 console.log('发送消息:', text) } } } </script> ``` 在上面的代码中,我们创建了一个MyChatComponent组件,并引入了vue-beautiful-chat组件。然后,我们在模板中使用BeautifulChat组件,并将messages属性绑定到组件中。messages属性用于显示聊天记录。我们还定义了一个onSend方法,用于处理发送的消息。 现在,我们可以在MyChatComponent组件中添加一些消息: ```javascript <script> export default { name: 'MyChatComponent', components: { BeautifulChat }, data() { return { messages: [ { text: '欢迎来到聊天室!', timestamp: new Date(), sender: { name: '系统消息' }, type: 'system' }, { text: '你好!', timestamp: new Date(), sender: { name: '张三' } }, { text: '你好,张三!', timestamp: new Date(), sender: { name: '李四' } } ] } }, methods: { onSend(text) { // 处理发送的消息 console.log('发送消息:', text) } } } </script> ``` 在这里,我们添加了一些初始消息,包括系统消息、张三的消息和李四的消息。 现在,我们可以在MyChatComponent组件中显示聊天记录和发送消息了。在浏览器中打开MyChatComponent组件,您将看到一个美观且易于使用的聊天界面。 以上就是使用vue-beautiful-chat组件的基本步骤,你可以根据自己的需求自定义组件的样式和功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值