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,该属性根据输入框的关键字和选择的分类筛选出匹配的项。

相关推荐
木斯佳9 小时前
前端八股文面经大全:携程前端一面(2026-04-17)·面经深度解析
前端·状态模式
2301_799073029 小时前
基于 Next.js + 火山引擎 AI 的电商素材智能生成工具实战——字节跳动前端训练营成果
javascript·人工智能·火山引擎
Java后端的Ai之路9 小时前
LangChain ReAct Agent 核心技术问答
前端·react.js·langchain
码喽7号9 小时前
Vue学习七:MockJs前端数据模拟
前端·vue.js·学习
NotFound48610 小时前
探究分享从对话到执行:OpenTiny NEXT 如何重塑前端智能化开发范式
前端
小满zs11 小时前
Next.js精通SEO第二章(robots.txt + sitemap.xml)
前端·seo
kyriewen11 小时前
你的首屏慢得像蜗牛?这6招让页面“秒开”
前端·面试·性能优化
算是难了11 小时前
Nestjs学习总结_3
前端·typescript·node.js
RONIN11 小时前
VUE开发环境配置基础(构建工具→单文件组件SFC→css预处理器sass→eslint)及安装脚手架
vue.js