用vue3写一个AI聊天室

这篇具有很好参考价值的文章主要介绍了用vue3写一个AI聊天室。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

效果图如下:

用vue3写一个AI聊天室,前端,学习笔记,前端,前端框架,vue.js

1、页面布局:

<template>
  <div class="body" style="background-color: rgb(244, 245, 248); height: 730px">
      <div class="container">
        <div class="right">
          <div class="top">AI问答</div>
          <div class="chat" ref="chatContainer">
            <div
              v-for="(item, i) in msgList"
              :key="i"
              :class="item.type == '1' ? 'rightMsg' : 'leftMsg'"
            >
              <img
                v-if="item.type == '0'"
                src="../assets/images/AI.png"
                alt=""
              />
              <div class="msg">{{ item.content }}</div>
              <img
                v-if="item.type == '1'"
                src="../assets/images/me.png"
                alt=""
              />
            </div>
            <!-- 
            <div v-if="msgList.length >= 10" class="separator">
              -------------- 本AI问答仅显示最近10条对话 --------------
            </div> -->
          </div>
          <div class="bottom">
            <input v-model="value" placeholder="请输入您想提问的内容" />
            <button @click="onSend">
              <img src="../assets/images/send.png" alt="发送" />
            </button>
          </div>
        </div>
      </div>
  </div>
</template>

2、封转函数(用户输入问题和AI回答问题):

const msgList = reactive([]);
//提问
const userQuestion = (question) => {
  var userMsg = {
    content: question,
    type: "1",
    id: Date.now(),
  };
  msgList.push(userMsg);
};
//回答
const AIReplay = (replay) => {
  var autoReplyMsg = {
    content: replay,
    type: "0",
    id: Date.now(),
  };
  msgList.push(autoReplyMsg);
};

3、从后端获取最近的10个对话:

const getMes = () => {
  getQandA({}).then((res) => {
    console.log(res);
    if (res.data.status == 200) {
      // 获取最近五条问答信息
      for (var i = 0; i < 5; i++) {
        userQuestion(res.data.data[i].inputMessage);
        AIReplay(res.data.data[i].aiResult);
      }
      scrollToNew();
    }
  });
};

4、为了使用户发送问题后内容滚动在最底处,写一个函数让其自动滚动,在发送信息和获取信息时调用该函数即可

// 等待DOM更新完成。自动滚动到最新发送的消息处
const scrollToNew = async () => {
  await nextTick();
  const chatContainer = document.querySelector(".chat");
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }
};

5、点击发送按钮,发送到后端进行处理:

const onSend = () => {
  // 发送用户输入的消息
  AIQandA({
    inputMessage: value.value,
  }).then((res) => {
    console.log(res);
    if (res.data.status == 200) {
      console.log(6666);
      AIReplay(res.data.data);
      scrollToNew();
    }
  });
  userQuestion(value.value);
  scrollToNew();
  value.value = "";
};

完整代码如下:文章来源地址https://www.toymoban.com/news/detail-861615.html

<template>
  <Header></Header>
  <div class="body" style="background-color: rgb(244, 245, 248); height: 730px">
    <header>
      <div class="cover">
        <img
          src="1.png"
          alt=""
          style="width: 100%; height: 100%"
        />
      </div>
    </header>
    <main>
      <div class="container">
        <div class="right">
          <div class="top">AI问答</div>
          <div class="chat" ref="chatContainer">
            <div
              v-for="(item, i) in msgList"
              :key="i"
              :class="item.type == '1' ? 'rightMsg' : 'leftMsg'"
            >
              <img
                v-if="item.type == '0'"
                src="../assets/images/AI.png"
                alt=""
              />
              <div class="msg">{{ item.content }}</div>
              <img
                v-if="item.type == '1'"
                src="../assets/images/me.png"
                alt=""
              />
            </div>
            <!-- 
            <div v-if="msgList.length >= 10" class="separator">
              -------------- 本AI问答仅显示最近10条对话 --------------
            </div> -->
          </div>
          <div class="bottom">
            <input v-model="value" placeholder="请输入您想提问的内容" />
            <button @click="onSend">
              <img src="../assets/images/send.png" alt="发送" />
            </button>
          </div>
        </div>
      </div>
    </main>
  </div>
  <foot></foot>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from "vue";
import Header from "../components/header.vue";
import foot from "../components/foot.vue";
import { AIQandA, getQandA } from "../api/AIApi";
const value = ref("");
const msgList = reactive([]);
onMounted(() => {
  getMes();
});
// 等待DOM更新完成。自动滚动到最新发送的消息处
const scrollToNew = async () => {
  await nextTick();
  const chatContainer = document.querySelector(".chat");
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }
};
const userQuestion = (question) => {
  var userMsg = {
    content: question,
    type: "1",
    id: Date.now(),
  };
  msgList.push(userMsg);
};
const AIReplay = (replay) => {
  var autoReplyMsg = {
    content: replay,
    type: "0",
    id: Date.now(),
  };
  msgList.push(autoReplyMsg);
};
const getMes = () => {
  getQandA({}).then((res) => {
    console.log(res);
    if (res.data.status == 200) {
      // 获取最近五条问答信息
      for (var i = 0; i < 5; i++) {
        userQuestion(res.data.data[i].inputMessage);
        AIReplay(res.data.data[i].aiResult);
      }
      scrollToNew();
    }
  });
};

const onSend = () => {
  // 发送用户输入的消息
  AIQandA({
    inputMessage: value.value,
  }).then((res) => {
    console.log(res);
    if (res.data.status == 200) {
      console.log(6666);
      AIReplay(res.data.data);
      scrollToNew();
    }
  });
  userQuestion(value.value);
  scrollToNew();
  value.value = "";
};
</script>

<style scoped lang="scss">
.body {
  color: #fff;
  font-weight: 900;
  letter-spacing: 2px;
  width: 100%;
  height: 100%;
  background-size: 50%;
  display: flex;
  align-items: center;
  position: relative;
}
main {
  /* border: 1px solid red; */
  width: 1400px;
  height: 600px;
  margin: 100px auto;
  display: flex;
}
.cover {
  position: absolute;
  top: 0px;
  z-index: 0;
  height: 180px;
  width: 1483px;
  left: 50%;
  margin-left: -754px;
  overflow: hidden;
}
.body {
  :deep(.slick-slide) {
    text-align: center;
    height: 100%;
    line-height: 100%;
    background: #364d79;
    overflow: hidden;
  }

  :deep(.slick-arrow.custom-slick-arrow) {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: #fff;
    background-color: rgba(31, 45, 61, 0.11);
    transition: ease all 0.3s;
    opacity: 0.3;
    z-index: 1;
  }

  :deep(.slick-arrow.custom-slick-arrow:before) {
    display: none;
  }

  :deep(.slick-arrow.custom-slick-arrow:hover) {
    color: #fff;
    opacity: 0.5;
  }

  :deep(.slick-slide h3) {
    color: #fff;
  }
}

.container {
  z-index: 1;
  // border: solid 1px #bebebe;
  width: 85%;
  height: 100%;
  margin: -6px auto;
  display: flex;
  justify-content: center;

  .right {
    flex: 1;
    // border-radius: 10px;
    background-color: white;
    display: flex;
    flex-direction: column;
    height: 600px;
    .top {
      height: 70px;
      background-color: rgba(147, 213, 255, 0.764);
      width: 100%;
      font-size: 22px;
      text-align: center;
      line-height: 70px;
    }

    .chat {
      flex: 1;
      max-height: 580px;
      overflow-y: auto;
      padding: 10px;
      .leftMsg,
      .rightMsg {
        display: flex;
        flex-direction: row;
        justify-content: start;
        align-items: center;
        margin: 10px;

        img {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          overflow: hidden;
          object-fit: cover;
          margin: 0 10px;
        }

        .msg {
          display: inline-block;
          padding: 10px;
          word-wrap: anywhere;
          max-width: 600px;
          background-color: #364d79;
          border-radius: 10px;
        }
      }

      .rightMsg {
        justify-content: end;

        .msg {
          color: black;
          background-color: #dfdfdf;
        }
      }
    }

    .bottom {
      height: 45px;
      display: flex;
      align-items: center;
      width: 80%;
      margin: 10px auto;

      input {
        width: 90%;
        border: 1px solid rgb(171, 171, 171);
        border-right: none;
        height: 40px;
        color: black;
        text-indent: 2px;
        line-height: 40px;
        border-radius: 10px 0 0 10px;
      }

      button {
        cursor: pointer;
        width: 10%;
        border: none;
        outline: none;
        height: 45px;
        border-radius: 0 10px 10px 0;
        background: linear-gradient(
          to right,
          rgb(146, 197, 255),
          rgb(200, 134, 200)
        );
      }
      img {
        width: 20px;
        height: 20px;
      }
    }
  }
}
.separator {
  color: rgb(133, 132, 132);
  text-align: center;
  font-size: 15px;
  font-weight: normal;
}
</style>

到了这里,关于用vue3写一个AI聊天室的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Vue+Nodejs 使用WebSocket创建一个简易聊天室

    使用vue编写前端页面,nodejs处理服务端消息,WebSocket进行实时通信 1.客户端 2. 服务端 使用的是nodejs

    2024年02月16日
    浏览(30)
  • python开发一个简单的聊天室

    使用python的twisted框架编写一个简单的聊天室 下面是基本架构 基本架构图 from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor user = {} class ChatReci(LineReceiver): #定义一个类,这里继承的是LineReceiver def init (self): #初始化2个变量 self.

    2023年04月23日
    浏览(27)
  • Java+Vue实现聊天室(WebSocket进阶-聊天记录)

    WebSocket 是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。 WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服

    2024年02月11日
    浏览(36)
  • 在线聊天室(Vue+Springboot+WebSocket)

    实现了一个简单的在线聊天室的前后端。前端用Vue实现,后端用Springboot实现。         在线聊天室的功能包括创建用户和显示在线用户列表、发送消息和显示消息列表、用户和消息列表实时更新这几点。以下是整体功能的活动图: 用户身份         进入聊天室的用户需

    2024年01月15日
    浏览(35)
  • 基于Java Socket写一个多线程的聊天室(附源码)

    Socket编程是在TCP/IP上的网络编程,但是Socket在上述模型的什么位置呢。这个位置被一个天才的理论家或者是抽象的计算机大神提出并且安排出来 ​ 我们可以发现Socket就在应用程序的传输层和应用层之间,设计了一个Socket抽象层,传输层的底一层的服务提供给Socket抽象层,S

    2024年02月10日
    浏览(37)
  • websocket+elementui+vue实现简易聊天室

    搭建服务端环境 安装socket.io 服务端基于node,js的express框架生成,所以写成模块,引入至app.js中 其中,io.sockets.emit用于向所有建立连接的客户端发送信息,socket.broadcast.emit用于向除发送方之外的客户端发送信息。 客户端基于vue和elementui 进入聊天页面后,先判断用户是否登录,

    2024年04月25日
    浏览(32)
  • websocket实现聊天室(vue2 + node)

    需求分析如图: 搭建的项目结构如图: 前端步骤: vue create socket_demo (创建项目) views下面建立Home , Login组件 路由里面配置路径 Home组件内部开启websocket连接 前端相关组件代码: Login组件 Home组件 router/index.js 后端步骤: 在项目外层创建server文件夹(src目录同级) npm init -y创建

    2024年01月22日
    浏览(31)
  • 基于SpringBoot+Vue+WebSocket的在线聊天室

    WebSocket 是一种在 Web 应用程序中实现双向通信的协议。它提供了一种持久连接,允许客户端和服务器之间进行实时数据传输,而无需进行频繁的请求和响应。 相对于传统的 HTTP 请求-响应模式,WebSocket 在客户端和服务器之间建立起一条长久的双向通信通道。这意味着服务器可

    2024年01月16日
    浏览(52)
  • 利用Java EE相关技术实现一个简单的Web聊天室系统

    利用Java EE相关技术实现一个简单的Web聊天室系统 (1)编写一个登录页面,登录信息中有用户名和密码,分别用两个按钮来提交和重置登录信息。 (2)通过请求指派来处理用户提交的登录信息,如果用户名为本小组成员的名字且密码为对应的学号时,跳转到LoginSuccess显示聊

    2024年02月07日
    浏览(27)
  • 【Unity工具,简单应用】Photon + PUN 2,做一个简单多人在线聊天室

    【Unity工具,简单学习】PUN 2,多人在线游戏开发,初步使用 需要有一定 UNITY 使用经验的开发者可以顺利阅读。 简单搭建一下大厅UI。 给 Laucher 节点一个 Launcher 脚本 Launcher 脚本如下,具体功能看注释 需要注意的是 PhotonNetwork.JoinOrCreateRoom(RoomName, new RoomOptions() { MaxPlayers = ma

    2024年02月08日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包