vue关键字搜索高亮标红

第一个参数msg是搜索出的字符串(后台返回的值)
第二个参数highLightStr是要高亮的字符串(输入框的值)

在utils文件夹中创建searchMessage.js,放入下方 highLightTableMsg 函数

export function highLightTableMsg(msg, highLightStr) {
    if (msg == null) {
      		msg = ''
    }
    if (highLightStr == null) {
      highLightStr = ''
    }
    if (msg instanceof Object) {
      msg = JSON.stringify(msg)
    }
    if (highLightStr instanceof Object) {
      highLightStr = JSON.stringify(highLightStr)
    }
    if (!(msg instanceof String)) {
      msg = msg.toString()
    }
    if (!(highLightStr instanceof String)) {
      highLightStr = highLightStr.toString()
    }
    var htmlStr = ''
    if (highLightStr.length > 0) {
      if (msg.indexOf(highLightStr) !== -1) {
        assemblyStr(msg, highLightStr)
      } else {
        htmlStr = '<span>' + msg + '</span>'
      }
    } else {
      htmlStr = '<span>' + msg + '</span>'
    }
    function assemblyStr(msgAssembly, highLightAssembly) {
      if (msgAssembly.indexOf(highLightAssembly) !== -1) {
        var length = highLightAssembly.length
        var start = msgAssembly.indexOf(highLightAssembly)
        htmlStr = htmlStr + '<span>' + msgAssembly.substring(0, start) + '</span>' + '<span class="log-hight-light">' + highLightAssembly + '</span>'
        msgAssembly = msgAssembly.substring(start + length, msgAssembly.length)
        assemblyStr(msgAssembly, highLightAssembly)
      } else {
        htmlStr = htmlStr + '<span>' + msgAssembly + '</span>'
      }
    }
    return htmlStr
  }
  

使用方法

<template>
  <div>
       <el-input
        clearable
        @keyup.enter.native="searchClick"
        v-model="searchValue"
        placeholder="请输入您想要查询的关键字"
      >
        <el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
      </el-input>
	<span class="search-value" v-html="seacrhMsg(msgList, searchValue)"></span>
  </div>
</template>
	

在页面中引入searchMessage.js

<script>
import { highLightTableMsg } from "@utils/searchMessage.js";
export default{
    data() {
	    return {
	    	searchValue: "",//搜索框的值
	    	msgList:[];//接收接口返回值
	    }
    },
	methods:{	
	  	seacrhMsg(val, searchValue) {
	      return highLightTableMsg(val, searchValue);//查询结果标红
	    },
	    searchClick(){//搜索事件
	    	//以搜索框的值为入参,调接口查询
	    	searchAPI(this.searchValue).then((res)=>{
	    		this.msgList = res.data;
	    	})
	    },
    }
}
<script/>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值