vue:实现商城分类
实现商城分类的步骤
在Vue中实现商城分类功能,可以通过组件化设计和状态管理来实现。以下是具体的实现方法。
创建分类组件
创建一个独立的分类组件,用于展示商城的分类列表。可以使用v-for指令动态渲染分类数据。
<template>
<div class="category-list">
<div
v-for="category in categories"
:key="category.id"
class="category-item"
@click="selectCategory(category.id)"
>
{{ category.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
categories: [
{ id: 1, name: '电子产品' },
{ id: 2, name: '服装' },
{ id: 3, name: '食品' }
]
};
},
methods: {
selectCategory(id) {
this.$emit('category-selected', id);
}
}
};
</script>
<style>
.category-list {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.category-item {
padding: 10px;
background: #f0f0f0;
border-radius: 5px;
cursor: pointer;
}
</style>
使用状态管理
如果项目较大,建议使用Vuex或Pinia管理分类状态。以下是使用Pinia的示例。
// stores/categoryStore.js
import { defineStore } from 'pinia';
export const useCategoryStore = defineStore('category', {
state: () => ({
categories: [
{ id: 1, name: '电子产品' },
{ id: 2, name: '服装' },
{ id: 3, name: '食品' }
],
selectedCategory: null
}),
actions: {
selectCategory(id) {
this.selectedCategory = this.categories.find(cat => cat.id === id);
}
}
});
动态加载分类数据
实际项目中,分类数据通常从后端API获取。可以使用axios或fetch异步加载数据。
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
export default {
setup() {
const categories = ref([]);
onMounted(async () => {
try {
const response = await axios.get('/api/categories');
categories.value = response.data;
} catch (error) {
console.error('加载分类失败:', error);
}
});
return { categories };
}
};
</script>
分类与商品联动
点击分类时,显示对应分类的商品列表。可以通过事件传递或状态管理实现联动。
<template>
<div>
<CategoryList @category-selected="loadProducts" />
<ProductList :products="products" />
</div>
</template>
<script>
import { ref } from 'vue';
import axios from 'axios';
export default {
setup() {
const products = ref([]);
const loadProducts = async (categoryId) => {
try {
const response = await axios.get(`/api/products?category=${categoryId}`);
products.value = response.data;
} catch (error) {
console.error('加载商品失败:', error);
}
};
return { products, loadProducts };
}
};
</script>
响应式布局优化
为了适应不同屏幕尺寸,可以使用CSS Grid或Flexbox实现响应式布局。
.category-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 15px;
padding: 20px;
}
@media (max-width: 768px) {
.category-list {
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
}
}
分类高亮显示
当前选中的分类可以通过动态类名高亮显示。
<template>
<div
v-for="category in categories"
:key="category.id"
class="category-item"
:class="{ 'active': selectedCategory === category.id }"
@click="selectCategory(category.id)"
>
{{ category.name }}
</div>
</template>
<style>
.active {
background: #42b983;
color: white;
}
</style>
以上步骤涵盖了商城分类功能的基本实现,包括组件设计、状态管理、数据加载和UI优化。根据项目需求,可以进一步扩展功能,如多级分类、分类筛选等。







