VUE3+TS,实现div块文字可编辑、可高亮关键词
1. div可编辑:contenteditable
属性
实现el-input
的效果
<div contenteditable="true">{{Text}}</div>
2. div文本高亮方式一:v-html
- 适合div块内关键词/一部分文字高亮
1. v-html
绑定文字
不在是{{}}
中写变量的方式
<div v-html="repairedText"></div>
//script中
let repairedText = ref<string>("")
2. 正则化实现文本高亮
v-html
绑定的文本才可以加载出来样式,{{Text}}
定义的变量直接显示span
语句- replace实现替换
- replace可以实现颜色替换、文本替换
repairedText.value = answerText.value.replace(item.original_text, `<span class="highlight-fixed-text">${item.original_text}</span>`)
//style
.highlight-fixed-text{
color:green;
}
3. div文本高亮方式二::style
或:class
- 适合div块的全部文字高亮
设置变量属性highlight
,根据属性值动态切换文本样式
style
<div v-for="(answerItem, answerIndex) in answerClaims" :key="answerIndex"
@click="highlightClaim(answerItem)" :class="answerItem.highlight ? 'highlighted-text' : ''">
script
:动态修改highlight
的取值
answerClaims.value.forEach((item) => {
if (item.data === element.data) {
item.highlight = true
} else {
item.highlight = false
}
})
style
.highlighted-text {
background-color: rgba(64, 158, 255, 0.3);
border-radius: 3px;
}
Tips
computed
:个人觉得,调接口获取的值推荐使用watch
,但是对接口结果进一步加工显示的数据,最好用computed
,它的优点就是一旦某个值发生变化后,页面会自动重新计算、重新渲染,不需要watch
一直监听repalce
:在样式动态修改上很有用!