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关键字搜索内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 在Vue3中使用provide和inject进行依赖注入的代码详解

    在Vue3中使用provide和inject进行依赖注入的代码详解

    在现代前端开发中,Vue.js已经成为了非常流行的框架之一,它提供了极大的灵活性和可维护性,今天我们要探讨的是Vue 3中的provide和inject功能,这是一种用于在组件树中进行依赖注入的方法,需要的朋友可以参考下
    2024-06-06
  • vue中状态管理器Pinia的用法详解

    vue中状态管理器Pinia的用法详解

    Pinia 是 Vue.js 的轻量级状态管理库,最近很受欢迎,它使用 Vue 3 中的新反应系统来构建一个直观且完全类型化的状态管理库,下面就跟随小编一起来学习一下它的具体使用吧
    2023-10-10
  • VUE中this.$router.push点了后hash地址改变了页面不跳转

    VUE中this.$router.push点了后hash地址改变了页面不跳转

    本文主要介绍了VUE中this.$router.push点了后hash地址改变了页面不跳转,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-11-11
  • vue中v-cloak的作用和原理解析

    vue中v-cloak的作用和原理解析

    v-cloak原理是先通过样式隐藏内容,然后在内存中进行值的替换,将替换的内容再反馈给界面,数据渲染完场之后,v-cloak 属性会被自动去除,本文详细介绍vue中v-cloak的作用和原理解析,感兴趣的朋友一起看看吧
    2023-09-09
  • vue动态设置img的src路径实例

    vue动态设置img的src路径实例

    今天小编就为大家分享一篇vue动态设置img的src路径实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-09-09
  • VUE的数据代理与事件详解

    VUE的数据代理与事件详解

    这篇文章主要为大家介绍了VUE的数据代理与事件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • vue实现网页语言国际化切换

    vue实现网页语言国际化切换

    这篇文章介绍了vue实现网页语言国际化切换的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-11-11
  • Vue.js学习教程之列表渲染详解

    Vue.js学习教程之列表渲染详解

    这篇文章主要给大家介绍了关于Vue.js列表渲染的相关资料,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-05-05
  • 利用Vue实现将图片转换为Base64编码的方法

    利用Vue实现将图片转换为Base64编码的方法

    这篇文章主要介绍了利用Vue实现将图片转换为Base64编码的方法,Base64是一种编码方式,用于将二进制数据转换成64个基于ASCII的可打印字符,这种编码可嵌入图像到HTML或CSS中,减少加载时间,解决跨域问题,并支持离线应用开发,需要的朋友可以参考下
    2024-10-10
  • vuex刷新之后数据丢失,数据持久化,vuex-persistedstate问题

    vuex刷新之后数据丢失,数据持久化,vuex-persistedstate问题

    这篇文章主要介绍了vuex刷新之后数据丢失,数据持久化,vuex-persistedstate问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03

最新评论