You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js页面加载默认展示全部商品,点击分类再过滤的实现方案

实现默认展示全部商品的标签页方案

核心修改思路

  1. 新增标签切换状态变量,默认指向「全部商品」
  2. 使用计算属性实现响应式的商品过滤逻辑
  3. 重构模板为标签栏+商品列表的结构,替代原来的分类展开模式

修改后的脚本代码

<script>
import axios from "axios";
export default {
  data() {
    return {
      categories: [],
      products: [],
      activeTab: 'all', // 默认选中「全部商品」标签
      price: null,
    };
  },
  computed: {
    filteredProducts() {
      // 根据当前激活标签过滤商品
      if (this.activeTab === 'all') {
        return this.products;
      }
      return this.products.filter(p => p.category._id === this.activeTab);
    }
  },
  methods: {
    switchTab(tabId) {
      this.activeTab = tabId;
    }
  },
  mounted() {
    // 并行请求商品和分类数据,优化加载效率
    Promise.all([
      axios.get("http://localhost:5000/api/products"),
      axios.get("http://localhost:5000/api/categories")
    ]).then(([productsRes, categoriesRes]) => {
      this.products = productsRes.data.products;
      this.categories = categoriesRes.data.categories;
    }).catch(err => {
      console.error('数据加载失败:', err);
    });
  }
};
</script>

修改后的模板代码

<!-- 标签切换栏 -->
<div class="tab-bar">
  <span 
    class="tab-item" 
    :class="{ active: activeTab === 'all' }"
    @click="switchTab('all')"
  >
    全部商品
  </span>
  <span 
    v-for="category in categories" 
    :key="category._id"
    class="tab-item"
    :class="{ active: activeTab === category._id }"
    @click="switchTab(category._id)"
  >
    {{ category.type }}
  </span>
</div>

<!-- 商品展示区域 -->
<div class="products-container">
  <div 
    v-for="product in filteredProducts" 
    :key="product._id"
    class="product-item"
  >
    {{ product.title }}
  </div>
  <!-- 空状态提示 -->
  <div v-if="filteredProducts.length === 0" class="empty-tip">
    暂无商品
  </div>
</div>

可选样式(提升视觉体验)

<style scoped>
.tab-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.tab-item {
  padding: 6px 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.tab-item.active {
  background-color: #42b983;
  color: #fff;
}
.products-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}
.product-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}
.empty-tip {
  text-align: center;
  padding: 40px;
  color: #999;
  grid-column: 1 / -1;
}
</style>

修改说明

  • 默认展示全部商品:通过activeTab: 'all'初始化状态,页面加载后自动触发全部商品的展示
  • 响应式过滤:使用计算属性filteredProducts替代原方法,自动响应activeTab变化,缓存计算结果提升性能
  • 标签页交互:重构为标签栏模式,点击标签切换activeTab,通过:class绑定激活样式,直观展示当前选中状态
  • 优化请求:用Promise.all并行请求商品和分类接口,减少页面加载等待时间
  • 空状态处理:添加无商品时的提示,避免页面空白

内容的提问来源于stack exchange,提问作者Tolu Arejibadey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 07:06:32