Vue.js中如何过滤栈追踪数组并优化表格列显示?
Vue.js中Bootstrap Table栈追踪内容的优化方案
需求背景
项目里用Vue结合Bootstrap Table展示后端返回的错误日志,其中stackTrace列内容太长,占了大量表格空间。需要实现两个效果:
- 表格里只显示栈追踪开头冒号前的异常类名(比如
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException) - 点击这个类名能查看完整的栈追踪内容
实现步骤
1. 核心修改思路
在computed的fields配置中,给stackTrace字段添加自定义格式化函数,同时用Bootstrap Vue的弹窗组件实现点击查看完整内容的交互。
2. 修改后的完整代码
<template> <b-container> <b-card class="mt-4"> <h5>{{ $t('events') }}</h5> <b-table :items="errors" :fields="fields" :per-page="[5, 10]" sort-desc primary-key="id" /> <!-- 展示完整栈追踪的弹窗 --> <b-modal id="stackTraceModal" title="完整栈追踪内容"> <pre class="p-2 bg-light">{{ fullStackTrace }}</pre> </b-modal> </b-card> </b-container> </template> <script> import { errorService } from '@/services/error'; import moment from 'moment'; export default { components: { // CommonTable, flapper // 原代码引入的组件未在模板中使用,可根据实际情况保留 }, data() { return { errors: null, fullStackTrace: '' }; }, computed: { fields() { return [ { key: 'priority', label: this.$t('errorLogs.priority'), sortable: true }, { key: 'creationDateTime', label: this.$t('creationDateTime'), formatter: date => moment(date).locale(this.$i18n.locale).format('L'), sortable: true }, { key: 'stackTrace', label: this.$t('errorLogs.stackTrace'), sortable: true, // 自定义格式化:提取类名并生成可点击文本 formatter: (value) => { // 分割字符串取冒号前的类名,处理无冒号的情况 const className = value.split(':')[0] || value; // 返回带点击事件的HTML文本 return `<a href="javascript:void(0)" @click="showFullStackTrace('${value}')">${className}</a>`; }, // 允许渲染HTML,否则点击事件不生效 formatterOptions: { raw: true } }, { key: 'errorMessage', label: this.$t('message'), sortable: true } ]; } }, methods: { load() { errorService.getErrorLogs().then(result => { this.errors = result.data; }); }, // 打开弹窗展示完整栈追踪 showFullStackTrace(stackTrace) { this.fullStackTrace = stackTrace; this.$bvModal.show('stackTraceModal'); } }, created() { this.load(); } }; </script> <style scoped> /* 可选:给可点击文本加样式,提示交互性 */ a { color: #007bff; cursor: pointer; } a:hover { text-decoration: underline; } </style>
3. 关键逻辑说明
- 类名提取:用
split(':')[0]分割栈追踪字符串,拿到冒号前的异常类名,同时兼容没有冒号的异常内容; - HTML渲染权限:设置
formatterOptions.raw: true,让表格允许渲染HTML,确保点击链接能触发事件; - 弹窗展示:借助Bootstrap Vue的
b-modal组件,点击时把完整栈追踪内容赋值给变量,再打开弹窗,用<pre>标签保留栈追踪的原始格式; - 样式优化:可选添加hover下划线样式,让用户一眼看出这是可点击的内容。
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

