vue2 增加左侧目录搜索功能

1:效果图如下

不多说上代码

2:引入方式 (fuse更多使用功能可以百度搜索)

方式一:cdn方式引入 fuse.js 轻量级模糊搜索,在html页面里面引入,引入后记得重启,不然不生效
https://cdn.bootcdn.net/ajax/libs/fuse.js/7.0.0/fuse.basic.min.js

方式二:也可以不用cdn方式,npm install fuse.js,需要在子组件里面加上这个 import Fuse from 'fuse.js'

3:可以把这个封装成一个组件使用  

父:

<headerSearch id="header-search" class="right-menu-item" />

import headerSearch from "./headerSearch";

components:{headerSearch}

子:就是下面代码 (cdn方式

<template>
    <div :class="{'show':show}" class="header-search">
      <svg-icon class-name="search-icon" icon-class="search" @click.stop="click" />
      <el-select
        ref="headerSearchSelect"
        v-model="search"
        :remote-method="querySearch"
        filterable
        default-first-option
        remote
        placeholder="请输入要搜索的左侧目录"
        class="header-search-select"
        @change="change"
      >
        <el-option v-for="item,index in options" :key="index" :value="item.item.urlLabel" :label="item.item.name.join(' > ')" />
      </el-select>
    </div>
  </template>
  
  <script>
  // fuse is a lightweight fuzzy-search module
  // make search results more in line with expectations
    //import Fuse from 'fuse.js'
  import path from 'path'
  
  export default {
    name: 'HeaderSearch',
    data() {
      return {
        search: '',
        options: [],
        searchPool: [],
        show: false,
        fuse: undefined
      }
    },
    computed: {
      routes() {
        return this.$store.getters.navList
      }
    },
    watch: {
      routes() {
        this.searchPool = this.generateRoutes(this.routes)
      },
      searchPool(list) {
        this.initFuse(list)
      },
      show(value) {
        if (value) {
          document.body.addEventListener('click', this.close)
        } else {
          document.body.removeEventListener('click', this.close)
        }
      }
    },
    mounted() {
      this.searchPool = this.generateRoutes(this.routes)
    },
    methods: {
      click() {
        this.show = !this.show
        if (this.show) {
          this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.focus()
        }
      },
      close() {
        this.$refs.headerSearchSelect && this.$refs.headerSearchSelect.blur()
        this.options = []
        this.show = false
      },
      change(val) {
        this.$router.push(val)
        this.search = ''
        this.options = []
        this.$nextTick(() => {
          this.show = false
        })
      },
      initFuse(list) {
        this.fuse = new Fuse(list, {
          shouldSort: true,
          threshold: 0.4,
          location: 0,
          distance: 100,
          maxPatternLength: 32,
          minMatchCharLength: 1,
          keys: [{
            name: 'name',
            weight: 0.7
          }, {
            name: 'urlLabel',
            weight: 0.3
          }]
        })
      },
      // Filter out the routes that can be displayed in the sidebar
      // And generate the internationalized title
      generateRoutes(routes, basePath = '/', prefixTitle = []) {
        let res = []
  
        for (const router of routes) {
          // skip hidden router
          if (router.hidden) { continue }
          // console.log(router)
          const data = {
            urlLabel: path.resolve(basePath, router.urlLabel),
            name: [...prefixTitle]
          }
  
          if (router && router.name) {
            data.name = [...data.name, router.name]
  
            // if (router.redirect !== 'noRedirect') {
              // only push the routes with title
              // special case: need to exclude parent router without redirect
              res.push(data)
            // }
          }
  
          // recursive child routes
          if (router.children) {
            const tempRoutes = this.generateRoutes(router.children, data.urlLabel, data.name)
            if (tempRoutes.length >= 1) {
              res = [...res, ...tempRoutes]
            }
          }
        }
        
        return res
      },
      querySearch(query) {
        if (query !== '') {
          this.options = this.fuse.search(query)
        } else {
          this.options = []
        }
        // console.log(this.options)
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .header-search {
    font-size: 0 !important;
  
    .search-icon {
      cursor: pointer;
      font-size: 18px;
      vertical-align: middle;
    }
  
    .header-search-select {
      font-size: 18px;
      transition: width 0.2s;
      width: 0;
      overflow: hidden;
      background: transparent;
      border-radius: 0;
      display: inline-block;
      vertical-align: middle;
  
      ::v-deep .el-input__inner {
        border-radius: 0;
        border: 0;
        padding-left: 0;
        padding-right: 0;
        box-shadow: none !important;
        border-bottom: 1px solid #d9d9d9;
        vertical-align: middle;
      }
    }
  
    &.show {
      .header-search-select {
        width: 210px;
        margin-left: 10px;
      }
    }
  }
  </style>
  

5:数据结构

        routes() {

        return this.$store.getters.navList

      }

navList对应的数据结构是这样的

有其他问题可以评论联系,*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。

### 集成搜索框至若依 Vue3 项目侧边导航栏 为了在若依 Vue3 项目的侧边导航栏中集成搜索框组件,需遵循特定步骤来确保功能正常运作并保持代码整洁。 #### 修改布局样式 首先,调整侧边栏宽度以适应新增加搜索框。这可以通过编辑 `variables.module.scss` 文件中的 `$base-sidebar-width` 变量完成[^3]: ```scss $base-sidebar-width: 200px; ``` 此操作为后续添加搜索框预留足够的空间。 #### 创建搜索框组件 接着,在 `components` 文件夹下创建一个新的 Vue 组件用于表示搜索框,命名为 `SearchBox.vue`: ```vue <template> <div class="search-box"> <input type="text" v-model="query" @keyup.enter="handleSearch" placeholder="请输入关键字..." /> <button @click="handleSearch">搜索</button> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; const query = ref(''); function handleSearch() { console.log('执行搜索:', query.value); } </script> <style scoped> .search-box { padding: 10px; } input, button { margin-right: 8px; } </style> ``` 上述代码定义了一个简单的输入框和按钮组合,当按下回车键或者点击按钮时触发搜索事件。 #### 更新路由配置 随后更新位于 `router/index.ts` 的路由设置,以便能够正确加载新创建的组件。虽然这部分主要涉及页面之间的跳转逻辑而非具体UI元素,但在某些情况下可能也需要相应调整以支持新的交互需求[^1]: ```typescript // 假设已经存在其他路径... { path: '/somePath', name: 'SomeComponentName', component: () => import('@/views/SomeView.vue') }, // 新增或修改现有路径以包含 SearchBox 组件作为子组件或其他形式嵌入 ``` #### 将搜索框加入侧边栏模板 最后一步是在负责显示左侧菜单结构的相关视图文件(通常是 `Layout.vue` 或者类似的容器组件)内部适当位置插入 `<SearchBox />` 标签: ```html <!-- Layout.vue --> <div class="sidebar-container"> <!-- 已有的菜单项... --> <!-- 插入自定义搜索--> <SearchBox /> <!-- 更多原有内容... --> </div> ``` 通过这种方式可以有效地将搜索框融入到现有的界面设计之中而不破坏整体的一致性和用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值