CSS + JS + Vue 实现商品分类选择功能

414 阅读1分钟

在电商网站中,商品分类选择是一个常见的功能,用户可以通过点击不同的分类来筛选商品。下面是一个使用 Vue.js、CSS 和 JavaScript 实现的商品分类选择功能的简单示例。

Vue 组件

创建一个 CategorySelector.vue 组件:

<template>
  <div>
    <h3>选择分类:</h3>
    <ul class="category-list">
      <li
        v-for="(category, index) in categories"
        :key="index"
        :class="{ active: activeCategory === category }"
        @click="selectCategory(category)"
      >
        {{ category.name }}
      </li>
    </ul>
    <div class="selected-products">
      <h3>选中分类的商品:</h3>
      <div v-for="(product, index) in filteredProducts" :key="index">
        {{ product.name }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeCategory: null,
      categories: [
        { id: 1, name: "电子产品" },
        { id: 2, name: "家居用品" },
        { id: 3, name: "图书" },
      ],
      products: [
        { id: 1, name: "手机", category: 1 },
        { id: 2, name: "电视", category: 1 },
        { id: 3, name: "桌子", category: 2 },
        // 更多商品...
      ],
      filteredProducts: [],
    };
  },
  methods: {
    selectCategory(category) {
      this.activeCategory = category;
      this.filteredProducts = this.products.filter(
        (product) => product.category === this.activeCategory.id
      );
    },
  },
};
</script>

<style scoped>
.category-list {
  list-style-type: none;
  padding: 0;
}

.category-list li {
  cursor: pointer;
  padding: 10px;
  border: 1px solid #ccc;
  margin: 5px;
  text-align: center;
}

.category-list li.active {
  background-color: #eee;
}

.selected-products {
  margin-top: 20px;
}
</style>

解释

  1. 数据和状态: 我们有一个 activeCategory 用于存储当前选中的分类,一个 categories 数组用于存储所有可用的分类,以及一个 products 数组用于存储所有的商品。

  2. 分类选择逻辑: 我们定义了一个 selectCategory 方法,该方法会设置 activeCategory 并筛选出该分类下的所有商品。

  3. 展示商品: 在模板中,我们用一个 div 来展示筛选出来的商品。

  4. 样式: 我们用简单的 CSS 来添加样式,例如,当用户选择一个分类时,该分类会有一个不同的背景颜色。

这个组件实现了一个基础的商品分类选择功能。你可以根据需要进行更多的定制和扩展,比如添加多级分类、价格筛选等。希望这个简单的示例能帮助你实现你需要的功能!