vue 通过query传参实现搜索和关键字高亮

最近这个项目里面,有一个全局搜索的功能,我们没有用ES全局搜索,只是做了一搜索管理页面,用来添加需要在搜索功能添加的接口、参数、展示的列等。搜索展示页面通过异步请求请求多个接口,来实现需要搜索的展示能,今天这是搜索中搜索关键字高亮是怎么实现的。vue路由通过query传参把关键字传给搜索页面,搜索页面点用接口,搜索有次关键字的信息,使用正则表达式进行全文匹配关键词,用带有样式的关键字替换全文关键字实现高亮。

1、路由页面

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";

Vue.use(Router);

export default new Router({
    // mode: "history",
    base: process.env.BASE_URL,
    routes: [{
            path: "/",
            name: "home",
            component: Home
        },
        {
            path: "/about",
            name: "about",
            // route level code-splitting
            // this generates a separate chunk (about.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () =>
                import ( /* webpackChunkName: "about" */ "./views/About.vue")
        },
        {
            path: "/fruits",
            name: "fruits",
            // route level code-splitting
            // this generates a separate chunk (about.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () =>
                import ( /* webpackChunkName: "about" */ "./views/fruits.vue")
        }
    ]
});```
2、搜索页面
```javascript
<template>
  <div>
    <div class="search fl">
      <div class="headfl" id="v-step1">
        <el-input
          class="headinput"
          style="border-radius: 20px;"
          placeholder="请输入内容"
          v-model="input"
          clearable
          @keyup.enter.native="searchEnterFun"
        >
          <el-button
            style=" color:#fff; font-size:16px;"
            slot="append"
            type="primary"
            icon="icon iconfont icon-fangdajing-copy"
            @click="searchClick"
          >
            <span style="display:inline-block; margin-left:10px;">
              搜索
            </span>
          </el-button>
        </el-input>
      </div>
    </div>
	</div>
</template>
<script>
  export default {
    data(){
      return {
        input:'',
      }
    },
    created(){
	  },
    mounted(){
    },
    methods: {
      // 热键
      searchEnterFun(e) {
        var keyCode = window.event ? e.keyCode : e.which;
        if (keyCode == 13 && this.input) {
          this.searchClick();
        }
      },
      searchClick() {
        var inputArray = this.input.split('')
        if(inputArray.length == 1){
          for(var I of inputArray){
            if(I == '_'){
              this.input = " "
            }
          }
        }
        if (this.input.trim()) {
          this.$router.push({
            path: "/fruits",
            query: {
              searchContent: this.input,
            },
          });
        }
      },
	  },
  }
</script>

3、搜索结果页面(带高亮)

<template>
    <div>
		<div>
            <ul id="box">
                <span v-for="(item,index) in searchInt" :key='index'>
                    <li v-html="item.int"></li>
                </span>
            </ul>
        </div>
	</div>
</template>
<script>
  export default {
    data(){
      return {
        searchValue:'',
        searchInt:[{
            int:'水果:草莓、菠萝、木瓜、哈密瓜、芒果、杏、李子、樱桃。'
        },{
            int:'水果:西瓜、木瓜、哈密瓜、山竹、樱桃、香蕉、芒果、火龙果。'
        },{
            int:'水果:苹果、香梨、山楂、橘子、桂圆、葡萄、木瓜、哈密瓜、荔枝、樱桃。'
        },{
            int:'水果:木瓜、哈密瓜、橘子、橙子、柚子、青枣、石榴、甘蔗、樱桃。'
        }]
      }
    },
    created(){
        console.log(this.$route.query.searchContent)
        this.searchValue = this.$route.query.searchContent;
        this.redHeight(this.searchValue)
	  },
    mounted(){
    },
    methods: {
        redHeight(value){
            this.searchInt.map((item, index) => {
                if (this.searchValue) {
                    /**
                     * 使用正则表达式进行全文匹配关键词
                     * ig : 表示 全文查找 ,忽略大小写
                     *  i : 忽略大小写
                     *  g : 全文查找
                     *
                     * 使用字符串的replace方法进行替换
                     * stringObject.replace('被替换的值',替换的值)
                     */
                    let replaceReg = new RegExp(this.searchValue, 'ig')
                    let replaceString = `<span style="color: #ed4014">${this.searchValue}</span>`
                    this.searchInt[index].int = item.int.replace(replaceReg, replaceString)
                }
            })
            
        }
	},
  }
</script>
<style type="text/css">
     #box{ 
	    height:200px; 
	    width:500px;
	    margin:50px auto;
	    border:2px solid #eee;
	    text-indent:20px;
    }
    #inpt{
        text-align:center;
    }
    li{
    	list-style-type: none;
    	margin: 10px 0;
    }
           
</style>
  • 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: '', keywords: ['Vue', '高亮'], content: '这是一段需要搜索的内容,其包含关键字 Vue高亮。' } }, computed: { highlightedContent() { let result = this.content this.keywords.forEach(keyword => { const regex = new RegExp(keyword, 'gi') result = result.replace(regex, '<span class="highlight">$&</span>') }) return result } }, methods: { highlightText() { // 触发 computed 的方法 } } } </script> <style> .highlight { color: red; font-weight: bold; } </style> ``` 在这个示例,我们在 data 定义了 searchText、keywords 和 content 三个变量,其 keywords 是需要搜索关键字列表。在模板使用 input 元素来渲染搜索框,并使用 v-model 将输入的内容绑定到 searchText 上,在 input 事件触发 highlightText 方法。使用 v-html 指令将 computed 返回的内容渲染为 HTML。在 computed 定义了一个方法 highlightedContent,使用 forEach 循环遍历关键字列表,使用正则表达式将匹配到的关键字用 span 标签包裹。最后在样式定义了高亮的样式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值