Vue关键字搜索功能实战小案例

 更新时间:2023年06月07日 14:35:25   作者:y17757773039  
在vue项目中,搜索功能是我们经常需要使用的一个场景,下面这篇文章主要给大家介绍了关于Vue关键字搜索功能的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

这里介绍两种方法:1、使用watch侦听方法 2、computed计算属性方法

页面结果:

第一种

<body>
    <div id="app">
        <!-- 搜索框 -->
        <input type="text" v-model:value="keyword">
        <!-- 数据,遍历filPerson-->
        <ul>
            <li v-for="p in filPerson" :key="p.id">{{p.name}}-{{p.age}}</li>
        </ul>
    </div>

    <script>
        var vm=new Vue({
            el:'#app',
            data:{
                keyword:'',
                persons:[
                    {id:1,name:'知花实央',age:20},
                    {id:2,name:'虎杖悠仁',age:18},
                    {id:3,name:'切嗣',age:16},
                    {id:4,name:'卫宫切嗣',age:33}
                ],
                filPerson:[]
            },
            //第一种写法
            watch:{
                keyword:{
                     //初始化,在生成vue时,先执行一遍handler
                    immediate:true,//作用:刚开始filPerson为空,所以要先给filPerson赋一次值
                    handler(val){
                        //person中包含val数据,赋值给filPerson
                        this.filPerson=this.persons.filter((p)=>{
                            return p.name.indexOf(val)!=-1
                        })
                    }
                }
            }

            //第二种写法
            // computed:{
            //     filPerson(){
            //         return this.persons.filter((p)=>{
            //             return p.name.indexOf(this.keyword)!=-1
            //         })
            //     }
            // }
        })
    </script>
</body>

第二种

相较于watch写法,computed写法看上去更加简洁,比如:

1、computed自身就是一种计算属性,不必再去data中新建一个属性。

2、计算属性实时更新,不用像watch方法,新建的filPerson初始值为空,还需要手动开启设置immediate=true初始化,令handler在vue实例创建后先运行一次,赋予初始值。

<body>
    <div id="app">
        <!-- 搜索框 -->
        <input type="text" v-model:value="keyword">
        <!-- 数据 -->
        <ul>
            <li v-for="p in filPerson" :key="p.id">{{p.name}}-{{p.age}}</li>
        </ul>
    </div>
    <script>
        var vm=new Vue({
            el:'#app',
            data:{
                keyword:'',
                persons:[
                    {id:1,name:'知花实央',age:20},
                    {id:2,name:'虎杖悠仁',age:18},
                    {id:3,name:'切嗣',age:16},
                    {id:4,name:'卫宫切嗣',age:33}
                ],
                // filPerson:[]
            },
            //第一种写法
            // watch:{
            //     keyword:{
            //          //初始化,在生成vue时,先执行一遍handler
            //         immediate:true,//作用:刚开始filPerson为空,所以要先给filPerson赋一次值
            //         handler(val){
            //             //过滤掉不包含keyword数据,再赋值给filPerson
            //             this.filPerson=this.persons.filter((p)=>{
            //                 return p.name.indexOf(val)!=-1
            //             })
            //         }
            //     }
            // }
            //第二种写法
            computed:{
                filPerson(){
                    return this.persons.filter((p)=>{
                        return p.name.indexOf(this.keyword)!=-1
                    })
                }
            }
        })
    </script>
</body>

其实watch方法和computed方法各有优劣,computed方法自己就是一种计算属性,很多时候直接给自己赋值,省去很多代码;但是watch方法能够做到跟多的细节操作,甚至computed能实现的,它都能实现,还能实现更多computed实现不了的细节。

补充:vue页面实现文本关键字检索,关键字高亮显示及定位功能

实现原理

  • 将相应的关键字用标签包裹,添加相应的样式,
  • 使用 dom.scrollIntoView() 方法实现定位功能

代码

html部分

<template>
    <div class="serach-box">                        
      <el-input                        
      placeholder="请输入关键字"                        
      prefix-icon="el-icon-search"                        
      v-model="inputLogValue"                        
      clearable                        
      size="small"                        
      @keyup.enter.native='clickSearch'>                        
      </el-input>                        
      <el-button type="primary" size="small" icon="el-icon-search" @click="clickSearch"></el-button>                        
    <div class="searchRight">                            
       <span class="item" style='margin-right:5px'>{{curIndex}}/{{matchCount}}</span>                                                           
       <el-tooltip class="item" effect="dark" content="上一个" placement="top">                                                
         <el-button @click="searchLast" icon="el-icon-arrow-up" circle type="text" size="mini" :disabled="matchCount==0"></el-button>                            
       </el-tooltip>                            
       <el-tooltip class="item" effect="dark" content="下一个" placement="top">                                                              
         <el-button @click="searchNext" icon="el-icon-arrow-down" circle type="text" size="mini" :disabled="matchCount==0"></el-button>                            
       </el-tooltip>                         
     </div>                    
   </div>
   <div class="log_content" ref='log_content' v-if="searchStatus" v-html="contentShow"></div>
<template>
<style lang="scss" scoped>
  .serach-box{        
    display: flex;        
    .el-input{            
      width: 300px;            
      .el-input__inner{                
        border-right: none;            
      }        
    }        
    .el-button{            
      border-radius: 0;            
      height: 32px;            
      box-sizing: border-box;        
    }        
    .searchRight{            
      height: 32px;            
      line-height: 32px;            
      padding: 0 10px;            
      background: #eee;            
      font-size: 14px;            
      color: #666;           
        .el-button+.el-button{                
          margin-left: 0;            
        }        
      }    
    }
    .log_content{            
      width: 100%;            
      height: calc(100% - 40px);            
      line-height: 20px;            
      background-color: #333333;            
      color: #f0f0f0;            
      font-size: 13px;            
      overflow: overlay;            
      padding: 0 20px ;            
      overflow-x:hidden;            
      word-wrap: break-word;            
      white-space: pre-wrap;            
      box-sizing: border-box;            
      padding-bottom: 20px;
      &::-webkit-scrollbar {                
        width: 10px;                
        height: 7px;                
        background-color: rgba(245, 245, 245, 0.1);                
        cursor: pointer;                
        z-index: 10;            
      }
      &::-webkit-scrollbar-thumb {                
        height: 20px;                
        border-radius: 10px;                
        background-color: #dddee0;                
        cursor: pointer;                
        z-index: 10;
      }
      &::-webkit-scrollbar-thumb:hover {                
        cursor: pointer;                
        background-color: #c7c9cc;            
      }        
   }
</style>

js部分

data() {        
   return {            
    logMessage:'',            
    inputLogValue:'',            
    lightIndex: 0,            
    curIndex:0,            
    matchCount: 0,            
    highlightStyle:'background: #ffff00;color:red;',            
    currentStyle:'background: #ff9632',
  }
},
watch:{
  inputLogValue: {            
    immediate: true,            
    handler (val) {                
      if(val==''){                            
        this.lightIndex=0                    
        this.curIndex=0                    
        this.matchCount=0                    
        this.searchStatus=0                
      }            
    }        
  },
},
methods:{
  scrollTo (index) {            
    this.$nextTick(() => {                
      let list = this.$el.querySelectorAll(`.search-hightlight`)                
      if (list[index]) {                    
         this.lightIndex = index                     
         list[index].scrollIntoView()                
      }            
    })       
  },        
  searchNext () {            
    this.$nextTick(() => {                
      let idx                
      if(this.lightIndex >= this.matchCount-1){                    
        this.lightIndex = 0                    
        idx = 0                
      }else{                    
        idx = this.lightIndex + 1                
      }                
        this.scrollTo(idx)            
      })        
    },        
  searchLast () {            
    this.$nextTick(() => {                
      let idx                
      if(this.lightIndex <= 0){                    
        idx = this.matchCount - 1                    
        this.lightIndex = this.matchCount - 1                
      }else{                    
        idx = this.lightIndex - 1                
      }                
      this.scrollTo(idx)            
    })        
  },        
  getMatchCount () {            
    this.$nextTick(() => {                
      let list = this.$el.querySelectorAll(`.search-hightlight`)                
      this.matchCount = list.length            
    })        
  },
  clickSearch(){            
    let reg = new RegExp(this.inputLogValue, 'ig')            
    let stringList = this.logMessage.split(reg)            
    if (stringList.length) {                
      this.searchStatus = 1                
      this.contentShow = ''                
      this.lightIndex = 0                
      for (let i = 0; i < stringList.length - 1; i++) {                    
        let style = i === this.lightIndex ? this.currentStyle : this.highlightStyle                       
        this.contentShow += `${stringList[i]}<font style="${style}" class='search-hightlight'>${this.inputLogValue}</font>`                
      }                
      this.contentShow += stringList[stringList.length - 1]                
      this.getMatchCount()                
      this.scrollTo(this.lightIndex)            
    }        
  },
}            

总结

到此这篇关于Vue关键字搜索功能实战案例的文章就介绍到这了,更多相关Vue关键字搜索内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue实现批量下载文件

    vue实现批量下载文件

    这篇文章主要为大家详细介绍了vue实现批量下载文件的方法(不走后端接口的方法),文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-12-12
  • vue实现标签页切换/制作tab组件详细教程

    vue实现标签页切换/制作tab组件详细教程

    在项目开发中需要使用vue实现tab页签切换功能,所以这里总结下,这篇文章主要给大家介绍了关于vue实现标签页切换/制作tab组件的相关资料,需要的朋友可以参考下
    2023-11-11
  • Vue实现计数器案例

    Vue实现计数器案例

    这篇文章主要为大家详细介绍了Vue计数器案例的实现方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-06-06
  • vue如何通过router-link或者button跳转到一个新的页面

    vue如何通过router-link或者button跳转到一个新的页面

    这篇文章主要介绍了vue如何通过router-link或者button跳转到一个新的页面,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • vue 组件中slot插口的具体用法

    vue 组件中slot插口的具体用法

    这篇文章主要介绍了vue 中slot 的具体用法,包括子组件父组件的代码介绍,需要的朋友可以参考下
    2018-04-04
  • 详谈vue中router-link和传统a链接的区别

    详谈vue中router-link和传统a链接的区别

    这篇文章主要介绍了详谈vue中router-link和传统a链接的区别,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • 如何在 vue3 中使用高德地图

    如何在 vue3 中使用高德地图

    这篇文章主要介绍了如何在 vue3 中使用高德地图,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-08-08
  • vscode下的vue文件格式化问题

    vscode下的vue文件格式化问题

    这篇文章主要介绍了vscode下的vue文件格式化问题,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-11-11
  • Vue 组件参数校验与非props特性的方法

    Vue 组件参数校验与非props特性的方法

    这篇文章主要介绍了Vue 组件参数校验与非props特性的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-02-02
  • vue3中安装并使用CSS预处理器Sass的方法详解

    vue3中安装并使用CSS预处理器Sass的方法详解

    Sass是一种CSS预处理器,它扩展了CSS的功能,提供了更高级的语法和特性,例如变量、嵌套、混合、继承和颜色功能等,这些特性可以帮助开发者更高效地管理和维护样式表,本文介绍vue3中安装并使用CSS预处理器Sass的方法,感兴趣的朋友一起看看吧
    2024-01-01

最新评论