Vue 显示关键词附近内容并高亮显示关键词

使用v-html显示内容,可识别内容里的标签

html 复制代码
<div v-html="surroundingContent(blog.content,input)"></div>
js 复制代码
  methods:{
	//获取内容 的关键词附近的内容
	surroundingContent(content,keyword) {
	  const keywordIndex = content.toLowerCase().indexOf(keyword.toLowerCase());
	  const startIndex = Math.max(0, keywordIndex - 10);
	  const endIndex = Math.min(content.length, keywordIndex + keyword.length + 10);
	  var slicedContent = content.slice(startIndex, endIndex);
	  return this.highlightedContent(slicedContent,keyword);
	},
	//高亮显示关键词
	highlightedContent(content,keyword) {
	  // 使用正则表达式匹配关键词,并用<span>标签包裹高亮显示
	  const highlighted = content.replace(new RegExp(keyword, 'gi'), match => {
		return `<span class="highlight">${match}</span>`;
	  });
	  return highlighted;
	},
	......
}
css 复制代码
<style scoped>
	:deep(.highlight) {
	  color: mediumblue;
	  background-color: yellow; /* 高亮颜色 */
	  font-weight: bold;
	}
	...
</style>

解决vue中使用v-html接收后端返回的数据时css样式不能修改的问题

产生问题的原因:由于style里面的scoped,导致v-html里面dom元素的类样式修改不了

解决方案1: 直接在dom的style的行内样式里面写,缺点是一般这个是值是后端直接给你的,行内样式需要拼接,很麻烦。

解决方案2: 在style scoped的下面再写一个style样式,不加scope,专门写这个v-html的样式,需要给v-html里面的dom加一个专门的类,避免全局样式污染到其他页面,因为这个style没有scope。

解决方案3:在style scoped中添加样式穿透:deep(选择器)【推荐使用解决方案3】

相关推荐
kyriewen8 分钟前
我扒了最近的前端面经——2026年面试不背八股文了,考这5样
前端·面试·ai编程
IT_陈寒27 分钟前
Redis的持久化配置把我坑惨了:你以为数据安全了?
前端·人工智能·后端
小徐_233335 分钟前
uni-app 项目别再从零搭了!3 个 Wot UI 起手模板怎么选?
前端·uni-app
张元清1 小时前
React useResizeObserver Hook:追踪元素尺寸变化(2026)
javascript·react.js
赵庆明老师1 小时前
Vben精讲:16-熟悉Vite前端工具链
前端
瑞瑞小同学4 小时前
处理echarts x轴内容过多,重叠问题
前端·javascript·echarts
HexCIer4 小时前
面向未来的原子化 CSS:UnoCSS 核心架构分析与 Tailwind CSS 现状
前端·css·vite
程序员黑豆4 小时前
鸿蒙应用开发中的单位详解:px、vp、fp、lpx
前端·harmonyos
像我这样帅的人丶你还4 小时前
MCP + npm:给五年前的老系统接上AI
前端·javascript·agent
南一Nanyi5 小时前
依赖注入和控制反转
前端·设计模式·nestjs