v-distpicker组件或Cascader 级联选择器
1.页面
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="姓名" prop="name">
<el-input v-model="form.name" placeholder="请输入姓名" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="联系电话" prop="telephone">
<el-input
v-model="form.telephone"
placeholder="请输入联系电话"
maxlength="11"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="所在地区" prop="district">
<!--方式1:安装v-distpicker组件 使用 npm 安装:npm install v-distpicker --save-->
<!-- <v-distpicker
@selected="onSelected"
:province="form.province"
:city="form.city"
:area="form.area"
></v-distpicker> -->
<!--方式2:使用cascader组件-->
<el-cascader
v-model="form.district"
placeholder="请选择"
:options="districtOptions"
clearable
filterable
style="width: 100%"
@change="onChange"
></el-cascader>
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item label="详细地址" prop="address">
<el-input
v-model="form.address"
type="textarea"
placeholder="请输入详细地址"
/>
</el-form-item>
</el-col>
</el-row>
</el-form>
2.js
<script>
import VDistpicker from "v-distpicker";//方式1 注册v-distpicker组件
import { getCascaderOptions } from '@/district/provinceCity';//方式2 导入provinceCity.js中的方法
export default {
name: "District",
components: { VDistpicker },
data() {
var checkPhone = (rule, value, callback) => {
if (!value) {
return callback(new Error("联系电话不能为空"));
} else {
const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
if (reg.test(value)) {
callback();
} else {
return callback(new Error("请输入正确的电话号码"));
}
}
};
return {
// 弹出层标题
title: "",
//所在地区组件
districtOptions: [],
// 表单参数
form: {},
// 表单校验
rules: {
name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
telephone: [
{
required: true,
validator: checkPhone,
trigger: "blur",
},
],
district: [
{ required: true, message: "所在地区不能为空", trigger: "blur" },
],
address: [
{ required: true, message: "详细地址不能为空", trigger: "blur" },
],
},
};
},
created() {
//调用省市区数据放入数组中(方式2)
this.districtOptions = getCascaderOptions();
},
methods: {
//所属地区(方式1)
// onSelected(data) {
// this.form.province = data.province.value;
// this.form.city = data.city.value;
// this.form.area = data.area.value;
// },
//所属地区(方式2)
onChange(data) {
this.form.province = this.form.district[0];
this.form.city = this.form.district[1];
this.form.area = this.form.district[2];
},
/** 修改按钮操作 */
//handleUpdate(row) {
// getAddress(row.addressId).then((response) => {
//将district合并到form中(方式2)
// this.form = {
// ...this.form,
// ...response.data,
// district: [
// response.data.province,
// response.data.city,
// response.data.area,
// ],
// };
// this.title = "修改";
// });
//},
},
};
</script>
3.省市区数据provinceCity.js文件(方式2)