前端商品多规格选择最简单解决办法

93 阅读1分钟

前端渲染的数据

    data: [{
	"id": null,
	"name": "颜色分类",
	"spuColors": [{
		"id": 2,
		"spuId": 9,
		"name": "紫色",
		"specificationId": 1
            }, {
                    "id": 3,
                    "spuId": 60,
                    "name": "绿色",
                    "specificationId": 1
            }, {
                    "id": 4,
                    "spuId": 61,
                    "name": "红色",
                    "specificationId": 1
            }, {
                    "id": 5,
                    "spuId": 62,
                    "name": "蓝色",
                    "specificationId": 1
            }, {
                    "id": 6,
                    "spuId": 63,
                    "name": "青色",
                    "specificationId": 1
            }, {
                    "id": 7,
                    "spuId": 64,
                    "name": "橙色",
                    "specificationId": 1
            }]
         }, {
            "id": null,
            "name": "尺码",
            "spuColors": [{
                    "id": 8,
                    "spuId": 60,
                    "name": "M",
                    "specificationId": 2
            }, {
                    "id": 9,
                    "spuId": 60,
                    "name": "S",
                    "specificationId": 2
            }]
    }]

初始数据进行处理

/**
 *给所有sku赋一个状态值
 */

this.data = this.data.forEach((item,index)=>{
	//item.status=false
	item.spuColors.forEach((items,indexs)=>{
		items.status=false
	})
})

前端页面显示

/**
 *以status状态判断规格是否选中
 */
<view style="margin:24rpx 0 34rpx ;" v-for="(item,cateNindex) in data">
	<text class="fs-32 bold ">{{item.name}}</text>
	<view class="flex flex-wrap " style="margin-top: 22rpx;">
	    <text :class="items.status==true?'text-btn bg-red color-ffffff ':'text-btn color-323232 border-none'" v-for="(items,spuCindex) in item.spuColors" @click="selsku(cateNindex,spuCindex)">{{items.name}}</text>
	</view>
</view>

进行选中函数进行处理

/**
 *通过组件向此函数传入选中分类以及规格的两级下标
 *选择规格
 */
selsku(idx,idxs) {
        this.data.forEach((item,goodsidx)=>{
             //当选中分类的下标等于循环的下标,去循环对应选择的那部分数据
             if(goodsidx==idx){
                   item.spuColors.forEach((items,spuidx)=>{
                   //把选中分类下所有规格状态初始化
                     items.status=false
                     //当选中规格的下标等于循环的下标,去改变选中规格的状态
                         if(idxs==spuidx){
                               items.status=true
                         }
                   })
              }

         })
}