VUE实现指定内根据关键字高亮

一、directives简介

        简介可以参考官方文档地址为:

        https://cn.vuejs.org/guide/reusability/custom-directives.html#directive-hooks

二、实现步骤

//html中
<div class="chat-record" v-highlight:content="keyWord">
    {{content}}
</div>


//script中
// 关键词keyword高亮
  directives: {
    highlight: {
      bind(el, binding) {
        const keyWord = binding.value;
        if(keyWord){
          const regex = new RegExp(keyWord, "gi");
          const content = el.textContent;
          el.innerHTML = content.replace(
                  regex,
                  '<span class="highlight">$&</span>'
          );
        }
      },
      update(el, binding) {
        const keyWord = binding.value;
        if(keyWord){
          const regex = new RegExp(keyWord, "gi");
          const content = el.textContent;
          el.innerHTML = content.replace(
                  regex,
                  '<span class="highlight">$&</span>'
          );
        }
      },
    },
  }

//style中
.highlight {
    color: #2878ff;
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Vue 中的搜索框中输入关键字后,将匹配到的内容高亮显示,可以遵循以下步骤: 1. 在 data 中定义一个变量来保存搜索关键字。 2. 在模板中使用 input 元素来渲染搜索框,并为其绑定一个 input 事件来监听输入内容变化。 3. 在模板中渲染需要搜索的内容,并使用 v-html 指令将内容渲染为 HTML。 4. 使用 computed 属性来实现关键字高亮的逻辑。在 computed 中定义一个方法,接收需要搜索的内容和搜索关键字,并使用正则表达式将匹配到的内容用 <span> 标签包裹,从而达到高亮的效果。 以下是一个示例代码: ``` <template> <div> <input type="text" v-model="searchText" @input="highlightText" placeholder="请输入搜索关键字"> <div v-html="highlightedContent"></div> </div> </template> <script> export default { data() { return { searchText: '', content: '这是一段需要搜索的内容,其中包含关键字 Vue高亮。' } }, computed: { highlightedContent() { const regex = new RegExp(this.searchText, 'gi') return this.content.replace(regex, '<span class="highlight">$&</span>') } }, methods: { highlightText() { // 触发 computed 中的方法 } } } </script> <style> .highlight { color: red; font-weight: bold; } </style> ``` 在这个示例中,我们在 data 中定义了 searchText 和 content 两个变量,其中 content 是需要搜索的内容。在模板中使用 input 元素来渲染搜索框,并使用 v-model 将输入的内容绑定到 searchText 上,在 input 事件中触发 highlightText 方法。使用 v-html 指令将 computed 中返回的内容渲染为 HTML。在 computed 中定义了一个方法 highlightedContent,使用正则表达式将匹配到的内容用 span 标签包裹。最后在样式中定义了高亮的样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值