我正在尝试在vuex中重构两个吸气剂。在我的状态下,我有一些对象的硬编码数组,如下所示:
state: {
color: 'All colors',
size: 'All sizes',
allShoes: [
{
productId: 1,
productno: 1234,
type: 'sneakers',
brand: 'Nike',
model: 'Air Zoom',
gender: 'Men',
size: ['39', '40', '41', '42', '43', '44', '45'],
price: 120,
color: 'red',
outerMaterial: 'Textile',
lining: 'Textile',
sole: 'Textile',
casingThickness: 'Thin lining',
fabric: 'Knitwear',
colors: ['red', 'blue', 'green'],
image: require('@/assets/images/nike-air-zoom.jpg'),
},
{
productId: 2,
productno: 1235,
type: 'sneakers',
brand: 'Adidas',
model: 'Ultra Boost',
gender: 'Men',
size: ['41', '42', '43', '44', '45'],
price: 130,
color: 'white',
outerMaterial: 'Textile',
lining: 'Textile',
sole: 'Textile',
casingThickness: 'Thin lining',
fabric: 'Knitwear',
colors: ['red', 'blue', 'orange'],
image: require('@/assets/images/adidas-ultra.jpg'),
},
You can see the full application here
如您所见,我想按颜色和尺寸过滤产品。下列吸气剂可以很好地工作:
getters: {
getProductById: (state) => (id) => {
return state.allShoes.find((shoe) => shoe.productId === id);
},
getProductsByGender: (state) => (gender) => {
if (state.color === 'All colors' && state.size === 'All sizes') {
return state.allShoes.filter((shoe) => shoe.gender === gender);
} else {
return state.allShoes.filter((shoe) => {
return (
(state.color === 'All colors' ||
(shoe.color === state.color && shoe.gender === gender)) &&
(state.size === 'All sizes' || shoe.size.includes(state.size)) &&
shoe.gender === gender
);
});
}
},
getProductsByType: (state) => (type) => {
if (state.color === 'All colors' && state.size === 'All sizes') {
return state.allShoes.filter((shoe) => shoe.type === type);
} else {
return state.allShoes.filter((shoe) => {
return (
(state.color === 'All colors' ||
(shoe.color === state.color && shoe.type === type)) &&
(state.size === 'All sizes' || shoe.size.includes(state.size)) &&
shoe.type === type
);
});
}
},
}
我遇到的问题是,这是一种重复的代码,我想将getProductsByGender和getProductsByType getter重构为一个。在getProductsByGender中,我使用了filter数组方法,但是我需要在我的对象中访问shoe.gender。在getProductsByType中,我需要访问shoe.type。我想不出一种重构这两个吸气剂的方法,或者可以这样使用它们吗?感觉好像我没有遵循DRY原则。有没有可能使用mixin的方法?如果有人能指出我正确的方向,我将不胜感激。
答案 0 :(得分:0)
我不认为您的功能本身很糟糕。您确实可以将其简化为一个。 请记住,如果您的网页应该包含数千个项目,则应考虑在后端使用某种形式的搜索引擎(弹性,阿尔戈利亚)进行此操作。
products(options) {
if (state.color === "All colors" && state.size == "All sizes") {
return state.allShoes.filter((shoe) => shoe[options.category] === options.filter);
} else {
return state.allShoes.filter((shoe) => {
return (
(state.color === "All colors" ||
(shoe.color === state.color && shoe[options.category] === options.filter)) &&
(state.size === "All sizes" || shoe.size.includes(state.size)) &&
shoe[options.category] === options.filter
);
});
}
}
// Example to call the function
const products = this.products({
category: "gender",
filter: "Female",
});