创新实训(十二) 项目开发——历史对话增加查询功能

必要性

随着对话记录的增加,根据对话名称conv_name查询对话对用户来说非常有必要实现。

实现

原来的history_chats.vue中使用了getChatList() 在onMounted时直接获取用户的所有对话记录,如果要实现查询功能,需要增加两个变量:

//查询得到的记录
const currentHistory = ref(null); // 使用 ref 创建一个响应式引用  
//所有对话
const allHistory = ref(null); // 使用 ref 创建一个响应式引用  

然后更改原有的getlist方法,将allHistory的value给chatHistory,可以保留原本的总的对话记录,同时将chatHistory作为返回的记录结果:

function getChatList() {
  let data = { "user_id": user_id.value };
  return getUserAllConversation(data).then(res => {
    if (res.code === 200) {
      allHistory.value = res.data.conversations; // 使用 .value 来更新 ref 的值  
      allHistory.value.reverse();
      allHistory.value.forEach(chat => {
        chat.formattedCreateTime = formatDateTime(chat.create_time); // 添加一个新字段来保存格式化后的时间  
      });
      console.log(allHistory.value);
      chatHistory.value=allHistory.value;
      return true;
    } else {
      console.log(res.msg);
    }
  }).catch(e => {
    console.error('获取对话列表失败:', e);
  });
}

在html中添加输入框和查询按钮:

    <div style="display: flex; align-items: center; margin: 20px 0;">
        <el-input v-model="input" style="width: 60%;height: 40px;" placeholder="请输入历史记录名称进行查询" clearable></el-input>
        <el-button type="primary"  size="large" @click="searchChatList()" style="margin-left: 10px;">查询</el-button>
    </div>

实现的查询函数和实现思路如下

  1. 检查输入框是否为空:

    • 如果输入框为空(即 input.value.trim() 为空字符串),则调用 getChatList() 函数获取全部的聊天记录,并将其赋值给 chatHistory.value
  2. 初始化 currentHistory 变量:

    • allHistory.value 的值赋给 currentHistory.value。这里 allHistory.value 存储了所有的聊天记录。
  3. 根据关键词筛选聊天记录:

    • 如果输入框中有关键词 keyword1,则使用 filter 方法从 currentHistory.value 中筛选出 conv_name 属性包含该关键词的聊天记录,并将结果赋给 currentHistory.value
  4. 更新 chatHistory.value:

    • 最后,将 currentHistory.value 的值赋给 chatHistory.value。这样就完成了根据关键词搜索聊天记录的功能。

主要逻辑是:先初始化 currentHistory 为全部聊天记录,然后根据用户输入的关键词,筛选出匹配的聊天记录,并更新 currentHistory,最后将 currentHistory 的值赋给 chatHistory,以供其他地方使用。

//进行搜索,替换当前的结果
const searchChatList = () =>{
  if(input.value.trim()===''){
    //为空返回全部
    getChatList();
    return;
  }
  const keyword1 =input.value.trim()
  
  // const list = JSON.parse(localStorage.getItem('list') as string)
  currentHistory.value = allHistory.value

  if (keyword1) {
    currentHistory.value = currentHistory.value.filter(item => item.conv_name.includes(keyword1));
  }
  chatHistory.value = currentHistory.value;

}

最终实现效果如下:

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值