需求:在新增中添加工作地址可以多选,地址的数据用后台返回来的数据不用网上开源的数据,树形结构渲染数据。在修改里可以查看和修改工作地址
网上开源省市区联动分享:js-export-excel vue-json-excel
<el-form-item label="工作地址:">
<div class="tree">
<el-tree :data="treeData" show-checkbox current-node-key="current" :node-key="defaultProps.id" ref="tree" highlight-current :props="defaultProps">
</el-tree>
</div>
</el-form-item>
data() {
return {
treeData: [],
defaultProps: {
children: 'children',
label: 'districtName',
id: 'districtId'
},
datalist: {
clientProjectNeedCitys: [
{
districtId: "",
districtPid: "",
districtName: "",
districtType: "",
districtHierarchy: ""
},
],
}
}
}
//掉接口并把数据渲染到树形结构上
getTreeData() {
this.$http({
url: this.$http.adornUrl("/api/admin/zpdistrict/tree_list"),
method: "post",
data: this.$http.adornData({})
}).then(({ data }) => {
this.treeData = data.data
//给修改里赋值的一步操作
if (this.datalist.clientProjectNeedCitys.length > 0 && this.type != 'add') {
let ids = this.datalist.clientProjectNeedCitys.map(item => { return item.districtId })
this.$nextTick(() => {
//setCheckedKeys()通过 keys 设置目前勾选的节点,使用此方法必须设置 node-key 属性
this.$refs.tree.setCheckedKeys(ids)
})
}
});
},
init(type, data) {
this.$refs.tree.setCheckedKeys([])
this.title = "新增"
if (type == 'add') {
this.getTreeData()
}
//提交表单
dataFormSubmit() {
if (this.type == 'add') {
//拿到选中的地址
let nodes = this.$refs.tree.getCheckedNodes() || [];
var arr = []
//选中地址里后台想要的字段循环遍历出来组成新的[{},{},{}....]
for (let i = 0; i < nodes.length; i++) {
let obj = {
districtName: nodes[i].districtName,
districtId: nodes[i].districtId,
districtPid: nodes[i].districtPid,
districtType: nodes[i].districtType,
districtHierarchy: nodes[i].districtHierarchy,
}
arr.push(obj)
}
this.clientProjectNeedCitys = arr
} this.$http({clientProjectNeedCitys: this.clientProjectNeedCitys })
}
//详情接口
detailed() {
this.$http({
url: this.$http.adornUrl("/api/admin/zp_client_project_need/info"),
method: "post",
data: this.$http.adornData({
})
}).then(({ data }) => {
console.log(data, "详情页面");
this.datalist = data.data;
this.datalist.clientProjectNeedCitys = data.data.clientProjectNeedCitys;
this.getTreeData()
});
},
补充:效验规则
<el-form-item label="工作地址:" prop="clientProjectNeedCitys">
<div class="tree">
<el-tree :data="treeData" show-checkbox current-node-key="current" :node-key="defaultProps.id" ref="tree" highlight-current :props="defaultProps">
</el-tree>
</div>
</el-form-item>
data() {
var validatePass = (rule, value, callback) => {
let arr = this.$refs.tree.getCheckedKeys()
if (arr.length == 0 || !arr) {
callback(new Error("请选择工作地址"));
} else {
callback();
}
};
}
clientProjectNeedCitys: [
{ required: true, validator: validatePass, trigger: "change" }
],