feat: 普通商品购买默认第一个规格
This commit is contained in:
@@ -127,7 +127,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, reactive, watch } from 'vue';
|
||||
import { computed, reactive, ref, watch } from 'vue';
|
||||
import sheep from '@/sheep';
|
||||
import { formatStock, convertProductPropertyList, fen2yuan } from '@/sheep/hooks/useGoods';
|
||||
|
||||
@@ -158,6 +158,74 @@
|
||||
return skuPrices;
|
||||
});
|
||||
|
||||
// 选中第一个可用的 SKU:
|
||||
// 单规格(propertyList.length === 0)→ 直接选中第一个有库存的 sku
|
||||
// 多规格 → 每个 property 维度选第一个有库存的 value,然后匹配 sku
|
||||
function selectFirstAvailableSku() {
|
||||
const skus = Array.isArray(skuList.value) ? skuList.value : [];
|
||||
// 1) 单规格 / 无属性
|
||||
if (!Array.isArray(propertyList) || propertyList.length === 0) {
|
||||
const first = skus.find((s) => Number(s?.stock) > 0) || skus[0];
|
||||
if (!first) {
|
||||
state.selectedSku = {};
|
||||
state.currentPropertyArray = {};
|
||||
return;
|
||||
}
|
||||
state.currentPropertyArray = {};
|
||||
first.goods_num = Math.min(1, Number(first.stock) || 1) > 0 ? 1 : 0;
|
||||
state.selectedSku = first;
|
||||
changeDisabled(false);
|
||||
return;
|
||||
}
|
||||
// 2) 多规格:取第一个 stock>0 的 sku,反推每个 property 的 value
|
||||
const first = skus.find((s) => Number(s?.stock) > 0) || skus[0];
|
||||
const nextProperty = {};
|
||||
propertyList.forEach((p) => {
|
||||
nextProperty[p.id] = '';
|
||||
});
|
||||
if (first && Array.isArray(first.properties)) {
|
||||
first.properties.forEach((prop) => {
|
||||
if (prop && (prop.propertyId || prop.id)) {
|
||||
const key = String(prop.propertyId || prop.id);
|
||||
const v = String(prop.valueId || prop.vid || prop.value || '');
|
||||
if (v) nextProperty[key] = Number(v) || v;
|
||||
}
|
||||
});
|
||||
}
|
||||
// 如果没匹配到,退化为每个 property 选第一个 value
|
||||
propertyList.forEach((p) => {
|
||||
if ((nextProperty[p.id] === '' || nextProperty[p.id] == null) && Array.isArray(p.values) && p.values.length) {
|
||||
const firstValue = p.values.find((v) => !v.disabled) || p.values[0];
|
||||
if (firstValue) nextProperty[p.id] = firstValue.id;
|
||||
}
|
||||
});
|
||||
state.currentPropertyArray = nextProperty;
|
||||
// 再次做禁用状态,保证其他维度上不可用的按钮标灰
|
||||
changeDisabled(false);
|
||||
// 从已选的属性组合里找出具体 sku
|
||||
const pick = getCanUseSkuList();
|
||||
if (pick.length) {
|
||||
const target = pick[0];
|
||||
const num = Math.min(1, Number(target.stock) || 1) > 0 ? 1 : 0;
|
||||
target.goods_num = num;
|
||||
state.selectedSku = target;
|
||||
} else {
|
||||
state.selectedSku = {};
|
||||
}
|
||||
}
|
||||
|
||||
// 每次打开弹窗(show 从 false 变 true)时自动默认选中第一个规格
|
||||
watch(
|
||||
() => props.show,
|
||||
(val) => {
|
||||
if (!val) return;
|
||||
// 先恢复默认 disabled 状态
|
||||
changeDisabled(false);
|
||||
selectFirstAvailableSku();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => state.selectedSku,
|
||||
(newVal) => {
|
||||
|
||||
Reference in New Issue
Block a user