需求分析:我们要实现一个简单版的ai聊天网页,聊天消息布局和 微信等日常聊天软件相似
思路分析 :
一
我们通过获取input框输入的值(text),调用api,获取ai回答的消息(response),把text和response都加入list数组中,动态渲染
二
动态渲染后消息布局应该是一左一右,和微信一致
这里使用flex布局,在消息div(container)动态渲染left类,right类两种消息,css格式如下
.container {
display: flex;
flex-direction: column;
// 高度自己定义,我这里示例比较简陋,设为的100px好实现 scrollToBottom函数
height: 80vh;
overflow-y: scroll;
}
.left {
align-self: flex-start;
border: 1px solid red;
width: 70vw;
}
.right {
align-self: flex-end;
border: 1px solid blue;
width: 70vw;
}
三
消息更新后div要到最底部
function scrollToBottom(div) {
div.scrollTop = div.scrollHeight;
}
所以实现如下,我这里用的是vue3,接入的是谷歌的gemini
<template>
<div>
<input type="text" v-model="article">
<button @click="run">点击</button>
<div class="container" ref="container">
<template v-for="item in list">
<div class="left" v-if="item.type === 0" v-bind:key="item.value">
{{ item.value }}
</div>
<div class="right" v-else v-bind:key="item">
{{ item.value }}
</div>
</template>
</div>
</div>
</template>
<script setup>
import { GoogleGenerativeAI } from "@google/generative-ai";
import { ref } from "vue"
let article = ref("")
let text = ref("")
let list = ref([])
let container =ref()
// token 是自己申请的密钥
const genAI = new GoogleGenerativeAI("token");
async function run() {
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = article.value
list.value.push({
value: prompt,
type: 0
})
article.value = '';
scrollToBottom(container.value)
const result = await model.generateContent(prompt);
const response = await result.response;
text.value = response.text();
await list.value.push({
value: text.value,
type: 1
})
scrollToBottom(container.value)
}
function scrollToBottom(div) {
div.scrollTop = div.scrollHeight;
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
height: 100px;
overflow-y: scroll;
}
.left {
align-self: flex-start;
border: 1px solid red;
width: 70vw;
}
.right {
align-self: flex-end;
border: 1px solid blue;
width: 70vw;
}
</style>
这就是大概思路了,具体还有很多小细节需要自己去优化。各位大佬如果有更好的思路可以在评论区提出。
如果觉得文章有帮到你,可以点个赞 (^-^)