Laravel Vue自定义筛选器失效:多选与计数功能修复求助
Laravel Vue 商品尺码筛选器修复方案
修复后的完整代码
筛选器选择HTML
<div class="filter-section"> <h3>尺码筛选</h3> <div class="size-options"> <label v-for="size in availableSizes" :key="size"> <input type="checkbox" :value="size" v-model="selectedSizes" @change="filterProducts" > {{ size }} <span>({{ getSizeCount(size) }})</span> </label> </div> </div>
商品列表HTML
<div class="product-list"> <div v-for="product in filteredProducts" :key="product.id" class="product-item"> <h4>{{ product.name }}</h4> <p>尺码:{{ product.sizes.join(', ') }}</p> </div> <p v-if="filteredProducts.length === 0">暂无匹配商品</p> </div>
Vue.js 逻辑代码
export default { data() { return { allProducts: [], // 从Laravel后端获取的全量商品数据 availableSizes: ['S', 'M', 'L', 'XL'], // 可选尺码集合 selectedSizes: [], filteredProducts: [] }; }, mounted() { // 实际项目中替换为axios请求Laravel接口获取数据 // axios.get('/api/products').then(res => { // this.allProducts = res.data; // this.filterProducts(); // }); // 模拟测试数据 this.allProducts = [ { id: 1, name: '商品A', sizes: ['S', 'M', 'L'] }, { id: 2, name: '商品B', sizes: ['M', 'XL'] }, { id: 3, name: '商品C', sizes: ['S', 'L'] }, { id: 4, name: '商品D', sizes: ['XL'] } ]; this.filterProducts(); }, methods: { filterProducts() { // 无选中尺码时显示全部商品 if (this.selectedSizes.length === 0) { this.filteredProducts = [...this.allProducts]; return; } // 筛选包含至少一个选中尺码的商品 this.filteredProducts = this.allProducts.filter(product => { return this.selectedSizes.some(selectedSize => product.sizes.includes(selectedSize)); }); }, getSizeCount(size) { // 基于全量商品计算该尺码的商品数量,不受当前筛选结果影响 return this.allProducts.filter(product => product.sizes.includes(size)).length; } } };
核心修复说明
- 多选筛选逻辑修正:将原筛选逻辑中可能错误的
every改为some,确保只要商品包含任意一个选中尺码就会被展示,符合多选筛选的预期。 - 计数逻辑独立:尺码计数直接基于全量商品数据计算,避免因当前筛选结果导致计数异常的问题。
- 实时触发筛选:通过
@change事件在复选框状态改变时立即执行筛选,保证界面实时更新。 - 初始化处理:页面加载完成后自动执行一次筛选,确保初始状态显示正确。
内容的提问来源于stack exchange,提问作者Mr. Khan
相关产品推荐
相关产品推荐

