You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue3(Vuetify)中实现API返回纯文本日志的搜索功能

实现日志文本的搜索过滤功能

核心思路

先把纯文本日志拆分成行数组,再用数组filter方法筛选包含搜索关键词的行,最后根据需求选择渲染数组或重新拼接成带换行的文本。

步骤1:改造Pinia Store

在你的Pinia Store中添加搜索关键词状态,同时用计算属性完成日志的拆分与过滤逻辑:

// stores/logStore.ts
import { defineStore } from 'pinia';

export const useLogStore = defineStore('log', {
  state: () => ({
    rawLogText: '', // 从API获取的原始纯文本日志
    searchKeyword: '', // 搜索输入框绑定的关键词
  }),
  getters: {
    filteredLogLines(): string[] {
      // 兼容Windows(\r\n)和Unix(\n)换行格式,同时过滤空行
      const lines = this.rawLogText.split(/\r?\n/).filter(line => line.trim() !== '');
      if (!this.searchKeyword.trim()) return lines;
      
      // 大小写不敏感的匹配逻辑
      const lowerKeyword = this.searchKeyword.toLowerCase();
      return lines.filter(line => line.toLowerCase().includes(lowerKeyword));
    },
    filteredLogText(): string {
      // 把过滤后的行重新拼接成带换行的文本,适配white-space:pre样式
      return this.filteredLogLines.join('\n');
    },
  },
  actions: {
    setRawLogText(text: string) {
      this.rawLogText = text;
    },
    setSearchKeyword(keyword: string) {
      this.searchKeyword = keyword;
    },
  },
});

步骤2:Vuetify组件中落地实现

在页面组件里绑定搜索框到Store的关键词,然后渲染过滤后的日志内容:

<template>
  <v-container>
    <!-- 搜索输入框 -->
    <v-text-field
      v-model="searchKeyword"
      label="搜索日志"
      placeholder="输入关键词过滤"
      variant="outlined"
      class="mb-4"
    />
    <!-- 日志展示区域 -->
    <v-card>
      <v-card-text class="log-content">
        <!-- 方式1:渲染拆分后的行数组(方便后续扩展高亮等功能) -->
        <div v-for="(line, idx) in filteredLogLines" :key="idx">{{ line }}</div>
        <!-- 方式2:用拼接后的文本,完全保留原始格式 -->
        <!-- <div>{{ filteredLogText }}</div> -->
      </v-card-text>
    </v-card>
  </v-container>
</template>

<script setup lang="ts">
import { useLogStore } from '@/stores/logStore';
import { storeToRefs } from 'pinia';
import { computed } from 'vue';

const logStore = useLogStore();
const { filteredLogLines, filteredLogText } = storeToRefs(logStore);
const { setSearchKeyword } = logStore;

// 绑定搜索框的双向数据
const searchKeyword = computed({
  get() {
    return logStore.searchKeyword;
  },
  set(val: string) {
    setSearchKeyword(val);
  },
});
</script>

<style scoped>
.log-content {
  white-space: pre-wrap;
  max-height: 600px;
  overflow-y: auto;
  font-family: monospace;
}
</style>

关键细节

  • 换行兼容:用split(/\r?\n/)同时处理Windows和Unix系统的换行符。
  • 空行过滤:避免日志末尾或中间的无效空行被展示。
  • 大小写兼容:统一转成小写后匹配,提升用户搜索体验。
  • 渲染选择:如果需要对匹配的关键词做高亮,用行数组渲染更灵活;如果只需保留原始格式,用拼接后的文本即可。

内容的提问来源于stack exchange,提问作者Divya Bharathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:24:51