当前位置:首页 > VUE

vue实现商品布局

2026-01-07 00:04:48VUE

Vue实现商品布局的方法

商品布局通常包括网格或列表展示、分页、筛选等功能。以下是基于Vue的实现方案:

基础结构搭建

使用Vue CLI或Vite创建项目,安装必要依赖如axios用于数据请求。商品数据通常通过API获取,存储在组件的data或Vuex/Pinia中。

data() {
  return {
    products: [],
    loading: false,
    pagination: {
      page: 1,
      pageSize: 12
    }
  }
}

网格布局实现

使用CSS Grid或Flexbox实现响应式网格。通过v-for循环渲染商品卡片:

<div class="product-grid">
  <div v-for="product in products" :key="product.id" class="product-card">
    <img :src="product.image" :alt="product.name">
    <h3>{{ product.name }}</h3>
    <p>¥{{ product.price }}</p>
  </div>
</div>
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}
.product-card {
  border: 1px solid #eee;
  padding: 15px;
  border-radius: 8px;
}

分页功能

实现分页控件,监听页码变化重新获取数据:

methods: {
  fetchProducts() {
    this.loading = true;
    axios.get('/api/products', {
      params: {
        page: this.pagination.page,
        size: this.pagination.pageSize
      }
    }).then(response => {
      this.products = response.data.items;
      this.total = response.data.total;
    }).finally(() => {
      this.loading = false;
    });
  }
}

筛选与排序

添加筛选表单,使用计算属性处理数据:

<select v-model="sortBy">
  <option value="price_asc">价格升序</option>
  <option value="price_desc">价格降序</option>
</select>
computed: {
  filteredProducts() {
    return this.products.sort((a, b) => {
      if (this.sortBy === 'price_asc') return a.price - b.price;
      return b.price - a.price;
    });
  }
}

性能优化

对于大量商品数据,考虑使用虚拟滚动或分页懒加载。可借助vue-virtual-scroller等库:

import { RecycleScroller } from 'vue-virtual-scroller';
components: { RecycleScroller }

状态管理

复杂场景建议使用Pinia管理商品状态,集中处理数据获取、缓存和更新逻辑:

// stores/product.js
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    filters: {}
  }),
  actions: {
    async fetchProducts() {
      const res = await api.getProducts(this.filters);
      this.products = res.data;
    }
  }
})

移动端适配

通过媒体查询调整网格列数和卡片样式:

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

vue实现商品布局

标签: 布局商品
分享给朋友:

相关文章

vue实现左右布局

vue实现左右布局

实现左右布局的方法 在Vue中实现左右布局可以通过多种方式完成,以下是几种常见的方法: 使用Flexbox布局 Flexbox是一种现代的CSS布局方式,可以轻松实现左右布局。 <tem…

vue实现上下布局

vue实现上下布局

实现上下布局的基本结构 在Vue中实现上下布局,可以通过CSS Flexbox或Grid布局快速完成。以下是一个基础模板示例: <template> <div class="…