使用v-html渲染,写一个高亮方法
<span class="title-name" v-html="highlightKeywords(name, keywords)"></span>
这里传入的name带了文件拓展名,所以先把名称从文件名里提取出来
// 高亮标题颜色highlightKeywords(name, keywords) {// 安全处理空值if (!name || typeof name !== 'string') return '';// 正则解释:// .*? 非贪婪匹配任意字符(尽可能少匹配)// (?=\.[^.]+$) 正向肯定预查:匹配后面紧跟着"点+扩展名"的位置const match = name.match(/.*?(?=\.[^.]+$)/);// 如果有匹配结果则返回,否则返回原名称(无扩展名的情况)const title = match ? match[0] : name;// console.log(title, '--title--')// console.log(match, '--match--')// 统一处理:将单个关键词转为数组,方便统一逻辑const keywordList = Array.isArray(keywords) ? keywords : [keywords];// 过滤空关键词const validKeywords = keywordList.filter(k => k && k.trim() !== '');if (validKeywords.length === 0) return title;// 构建正则表达式:匹配所有关键词(不区分大小写)// 转义特殊字符,避免正则语法错误const escapedKeywords = validKeywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // 转义正则特殊字符);const regex = new RegExp(`(${escapedKeywords.join('|')})`, 'gi');// 替换匹配到的关键词,添加高亮样式return title.replace(regex, (match) => {return `<span style="color: blue">${match}</span>`;});},