首先,要確保你的開發環境是vue+element框架。然後就可以開始了
- 添加一個按鈕用於打開模態框
<el-button type="primary" @click="handleSkuProperties">SKU屬性</el-button>
- 設計一個組件用於動態添加表單,我這兒使用的是模態框。裏面是卡片和表格處理數據
<!--SKU屬性維護的模態框-->
<el-dialog title="SKU屬性管理" :visible.sync="skuDialogVisible" width="60%">
<!--卡片 外層的卡片代表者一個sku屬性-->
<el-card class="box-card" v-for="skuProperty in skuProperties" style="margin-bottom: 5px">
<!--內層的div代表sku屬性的選項-->
<div slot="header" class="clearfix">
<span>{{skuProperty.specName}}</span>
</div>
<div v-for="index in skuProperty.options.length+1" :key="index" class="text item">
<el-input v-model="skuProperty.options[index-1]" style="width:80%"></el-input>
<el-button icon="el-icon-delete" @click="skuProperty.options.splice(index-1,1)"
style="width:10%"></el-button>
</div>
</el-card>
<el-table :data="skus" border style="width: 100%">
<el-table-column type="index" width="50"></el-table-column>
<template v-for="(value,key) in skus[0]">
<!--更改價格和庫存單元格和標題-->
<el-table-column v-if="key=='price'" :prop="key" label="價格">
<template scope="scope">
<el-input v-model="scope.row.price"></el-input>
</template>
</el-table-column>
<el-table-column v-else-if="key=='availableStock'" :prop="key" label="庫存">
<template scope="scope">
<el-input v-model="scope.row.availableStock"></el-input>
</template>
</el-table-column>
<!--隱藏sku_index屬性-->
<el-table-column v-else-if="key!='sku_index'" :prop="key" :label="key">
</el-table-column>
</template>
</el-table>
<span slot="footer" class="dialog-footer">
<el-button @click="skuDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="subSkuProperties">確 定</el-button>
</span>
</el-dialog>
- 在data(){}裏面添加數據源和模態框的控制屬性
skuDialogVisible: false,//sku屬性模態框 skuProperties: []
- 數據源的數據自行通過後臺獲取,也可以界面把數據寫死了,測試一下看看界面展示對不對。這裏給出測試數據,看是否動態搭配屬性值
skuProperties = [
{
"specName": "膚色",
"options": ["黑色", "黃色"]
},
{
"specName": "年齡",
"options": ["蘿莉", "御姐"]
},{
"specName": "體型",
"options": ["腿長1米8", "身高1米5"]
}]
這裏是動態監聽事件,最重要的一環,通過動態監聽事件以及reduce方法,可以達到在模態框上輸入數值,然後自動搭配顯示結果組成表格的效果
watch: {
skuProperties: {//深度監聽,可監聽到對象、數組的變化
handler(val, oldVal) {
//動態生成skus值
let res = this.skuProperties.reduce((pre, cur) => {
let result = [];
pre.forEach(e1 => {
e1.sku_index = (e1.sku_index || '') + "_";
for (let i = 0; i < cur.options.length; i++) {
let e2 = cur.options[i];
let temp = {}
Object.assign(temp, e1);
temp[cur.specName] = e2;
temp.sku_index += i;
result.push(temp);
}
})
return result;
}, [{}])
//添加價格
res.forEach(e1 => {
e1.price = 0;
e1.availableStock = 0;
e1.sku_index = e1.sku_index.substring(1);
})
this.skus = res;
},
deep: true
}
}
若是這個看不懂的話,還可以下載我的源碼基於springCloud微服務的系統的商品模塊裏面,有這個的完整實現,包括數據庫