目录
步骤1:数据库
步骤1.1:省市区数据库(无需建表)
npm install element-china-area-data -S
注:V6版本不支持中国港澳台地区,如需要应使用V5.0.2版本
注:如果仅使用省市区三级联动可直接跳转到4.1
步骤1.2:自定义数据MySQL建表
首先我们要了解级联选择器options数据结构
options数组包含value(值),label(值),children(数组)
value 指定选项的值为选项对象的某个属性值
label 指定选项标签为选项对象的某个属性值
children 指定选项的子选项为选项对象的某个属性值
我们建表应设置三个字段,value(主键),label,parent_value(外键)
自定义模拟数据库已上传
步骤2:后端实体类改动(自定义数据)
例:
/**
*
* @TableName shop
*/
@TableName(value ="shop")
@Data
public class Shop implements Serializable {
/**
* 商铺id
*/
@TableId(type = IdType.AUTO)
private Integer value;
/**
* 商铺名称
*/
private String label;
//变动
@TableField(exist = false)
private List<Kind> children;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
注:在父实体类中引入子实体类数组
步骤3:后端控制层(自定义数据)
@Autowired
GoodsService goodsService;
@Autowired
KindService kindService;
@Autowired
ShopService shopService;
@RequestMapping("one")
public R list() {
List<Shop> shopList = shopService.list();
for (Shop shop : shopList) {
QueryWrapper<Kind> kindQueryWrapper = new QueryWrapper<>();
kindQueryWrapper.eq("parent_value", shop.getValue());
List<Kind> kindList = kindService.list(kindQueryWrapper);
shop.setChildren(kindList);
for (Kind kind : kindList) {
QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
goodsQueryWrapper.eq("parent_value", kind.getValue());
List<Goods> goodsList = goodsService.list(goodsQueryWrapper);
kind.setChildren(goodsList);
}
}
return R.successed(shopList);
}
步骤4:前端
4.1省市区三级联动
<template>
<div>
<el-cascader
size="large"
:options="regionData"
v-model="xxx"
style="width: 240px;">
</el-cascader>
</div>
</template>
<script>
import {regionData} from "element-china-area-data";
export default {
data() {
return {
regionData,
xxx: []
}
},
methods: {}
}
</script>
4.2自定义三级联动
<template>
<div>
<el-form-item label="商品名称:">
<el-cascader size="large" :options="selectData" v-model="xxx"
style="width: 240px;"></el-cascader>
</el-form-item>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
selectData: [],
}
},
methods: {
store() {
axios.post("http://localhost:8102/store/one").then(r => {
this.selectData = r.data.data;
})
}
}, created() {
this.store();
}
}
</script>
注:v-model="xxx"为用户选中数据的value值
注:如果已建表,但字段名不相同可以使用