vue多条件查询

复制代码
<template>
  <div>
    <input type="text" v-model="keyword" placeholder="关键字">
    <select v-model="category">
      <option value="">所有分类</option>
      <option v-for="cat in categories" :value="cat">{{ cat }}</option>
    </select>
    <button @click="search">查询</button>
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }} - {{ item.category }}
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, computed } from 'vue';

export default {
  setup() {
    const keyword = ref('');
    const category = ref('');
    const items = ref([
      { id: 1, name: '物品1', category: '分类1' },
      { id: 2, name: '物品2', category: '分类2' },
      { id: 3, name: '物品3', category: '分类1' },
      { id: 4, name: '物品4', category: '分类3' }
    ]);
    const categories = ['分类1', '分类2', '分类3'];

    const filteredItems = computed(() => {
      return items.value.filter(item => {
        const isMatchingKeyword = item.name.toLowerCase().includes(keyword.value.toLowerCase());
        const isMatchingCategory = !category.value || item.category === category.value;
        return isMatchingKeyword && isMatchingCategory;
      });
    });

    const search = () => {
      // 执行搜索逻辑(例如调用接口)
      // 根据输入框和条件筛选出匹配的项
      // 更新 filteredItems
    };

    return {
      keyword,
      category,
      categories,
      filteredItems,
      search
    };
  }
};
</script>

在上述例子中,我们使用了Vue 3的refcomputed函数。首先,我们创建了名为keywordcategoryitems的响应式引用。然后,我们使用computed函数创建了一个计算属性filteredItems,该属性根据输入框的关键字和选择的分类筛选出匹配的项。

相关推荐
freewlt5 小时前
前端性能优化实战:从 Lighthouse 分数到用户体验的全面升级
前端·性能优化·ux
小小亮015 小时前
Next.js基础
开发语言·前端·javascript
华洛5 小时前
我用AI做了一个48秒的真人精品漫剧,不难也不贵
前端·javascript·后端
Amumu121386 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
Novlan16 小时前
我把 Claude Code 里的隐藏彩蛋提取出来了——零依赖的 ASCII 虚拟宠物系统
前端
Sgf2276 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
IAUTOMOBILE6 小时前
Python 流程控制与函数定义:从调试现场到工程实践
java·前端·python
好大哥呀7 小时前
C++ Web 编程
开发语言·前端·c++
爱学习的小仙女!7 小时前
面试题 前端(一)DOCTYPE作用 标准模式与混杂模式区分
前端·前端面试题
小小小小宇8 小时前
前端转后端基础- 变量和类型
前端