当前位置:首页 > VUE

vue 实现商城分类

2026-03-10 02:12:49VUE

Vue 实现商城分类功能

数据结构设计

商城分类通常采用树形结构,需设计包含 idnamechildren 等字段的嵌套数据。例如:

[
  {
    "id": 1,
    "name": "电子产品",
    "children": [
      {
        "id": 101,
        "name": "手机",
        "children": []
      }
    ]
  }
]

组件拆分

  • 分类侧边栏组件:用于展示一级分类,通过点击切换当前分类。
  • 子分类展示组件:根据当前选中的一级分类动态渲染二级或三级分类。
  • 商品列表组件:展示当前分类下的商品数据。

动态渲染分类

使用 v-for 递归渲染嵌套分类结构:

<template>
  <div v-for="category in categories" :key="category.id">
    <div @click="selectCategory(category)">{{ category.name }}</div>
    <div v-if="category.children.length > 0" class="sub-categories">
      <CategoryList :categories="category.children" />
    </div>
  </div>
</template>

状态管理

通过 Vuex 或 Pinia 管理当前选中的分类 ID,实现跨组件状态共享:

// Pinia 示例
export const useCategoryStore = defineStore('category', {
  state: () => ({
    currentCategoryId: null
  }),
  actions: {
    setCurrentCategory(id) {
      this.currentCategoryId = id
    }
  }
})

路由参数绑定

将分类 ID 与路由参数绑定,支持直接访问特定分类页:

const routes = [
  {
    path: '/category/:id',
    component: CategoryPage,
    props: true
  }
]

数据请求优化

使用 computed 缓存分类数据,避免重复请求:

vue 实现商城分类

const categories = computed(() => store.getters.getCategories)

交互增强

  • 添加分类展开/折叠动画
  • 使用 active 类标记当前选中分类
  • 实现面包屑导航显示分类路径

移动端适配

  • 侧边栏改为滑动抽屉式布局
  • 通过手势事件支持左右滑动切换分类
  • 使用 vw/vh 单位确保布局响应式

完整实现需结合具体业务需求调整数据结构和交互细节。

标签: 商城vue
分享给朋友:

相关文章

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现treeview

vue实现treeview

Vue 实现 TreeView 的方法 使用递归组件实现 TreeView 递归组件是 Vue 中实现 TreeView 的常见方式。通过组件调用自身,可以轻松处理嵌套的树形结构数据。 <te…

vue轮播实现

vue轮播实现

Vue 轮播实现方法 使用第三方库(推荐) 安装 swiper 或 vue-awesome-swiper 库,快速实现功能丰富的轮播效果。 以 vue-awesome-swiper 为例: npm…

vue实现xterm

vue实现xterm

在 Vue 中集成 Xterm.js Xterm.js 是一个基于 TypeScript 的前端终端组件库,可用于在浏览器中实现终端功能。以下是在 Vue 项目中集成 Xterm.js 的详细步骤。…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能可以通过多种方式完成,以下是几种常见的方法: 使用数组模拟队列 队列遵循先进先出(FIFO)原则,可以用数组的 push 和 shift 方法模拟入队…