首页 前端知识 vue聊天对话ai流式输出

vue聊天对话ai流式输出

2024-06-07 23:06:20 前端知识 前端哥 918 75 我要收藏

在这里插入图片描述


<template>
  <div class="talkContent">
    <div class="talkShow">
      <div :class="[(item.person=='mechanical')?'mechanicalTalk':'mineTalk']" v-for="(item,index) in talkList" :key="index">
          <span>{{item.say}}</span>
      </div>
    </div>
    <div class="talkInput">
      <form @submit.prevent="getQuestion" class="userSearch">
        <el-input
          placeholder="请输入内容"
          v-model="contentVal"
          size="small">
          <i slot="suffix" class="el-input__icon el-icon-position" style="cursor: pointer;" @click="getQuestion"></i>
        </el-input>
     </form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      talkList: [
        { id:"1", person: 'mechanical', say: '你好,有什么可以帮到你呢?' },
      ],
      isMine: 1,
      contentVal: '',
    };
  },
  methods: {
    getQuestion() {
      if (this.contentVal == '') {
        this.$message.error('请输入内容');
        return;
      }
      // admin提问数据push()
      this.talkList.push({ id: Date.now(), person:'admin', say: this.contentVal });
      // 清空输入栏数据
      this.contentVal = '';
      this.getAnswer();
    },
    async getAnswer() {
      // 调用API获取回答, 模拟后端返回的数据流式输出
      const data ='文字逐个展示,文字逐个展示,文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示文字逐个展示';
      // mechanical 模拟回答
      this.talkList.push({ id: Date.now(), person:'mechanical', say: '...' });
      // 流式输出文字逐个展示
      let text = "";
      const length = this.talkList.length;
      for (let i = 0; i < data.length; i++) {
        text += data.charAt(i);
        await new Promise((resolve) => {
          setTimeout(resolve, 50)
        });
        this.talkList[length - 1].say= text;
      }
    }
  },
};
</script>

<style scoped>
.talkContent {
  margin: 50px auto 0;
  font-size: 14px;
}

.talkShow {
  height: 400px;
  margin: 10px auto 0;
  overflow: auto;
}

.talkInput {
  margin: 10px auto 0;
  display: flex;
}

.mechanicalTalk {
  margin: 10px;
}

.mechanicalTalk span {
  display: inline-block;
  background: white;
  border-radius: 10px;
  padding: 5px 10px;
  border: 1px solid rgb(214, 216, 219);
  border-top-left-radius: 0px;
  word-break: break-all;
  text-align: left;
}

.mineTalk {
  margin: 10px;
  text-align: right;
}

.mineTalk span {
  display: inline-block;
  border-radius: 10px;
  border-top-right-radius: 0px;
  background: #409eff;
  color: #fff;
  padding: 5px 10px;
  word-break: break-all;
  text-align: left;
}

</style>

转载请注明出处或者链接地址:https://www.qianduange.cn//article/11353.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!