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】

相关推荐
布局呆星1 小时前
Vue3 计算属性|从基础缓存到可读写
前端·javascript·vue.js
ZPC82108 小时前
如何创建一个单例类 (Singleton)
开发语言·前端·人工智能
紫_龙8 小时前
最新版vue3+TypeScript开发入门到实战教程之重要详解readonly/shallowReadOnly
前端·javascript·typescript
roamingcode10 小时前
前端 AI Agent 多智能体协作架构:从对抗式排查到工作流解耦
前端·人工智能·架构·agent·team
蓝莓味的口香糖11 小时前
【vue】初始化 Vue 项目
前端·javascript·vue.js
aikongmeng11 小时前
【Ai】Claude Code 初始化引导
javascript
光影少年11 小时前
数组去重方法
开发语言·前端·javascript
我命由我1234511 小时前
浏览器的 JS 模块化支持观察记录
开发语言·前端·javascript·css·html·ecmascript·html5
weixin_4434785112 小时前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
武藤一雄12 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore