- 引入资源文件region.json,在git下载,我这边选择的是省市区
2. 页面代码
先引入资源文件,再对文件进行初始处理即可
<template>
<view class="content">
<view class="form_item">
<view class="title">地区</view>
<picker mode="multiSelector" @change="okReginon" @columnchange="bindMultiPickerColumnChange" :value="regionIndex" :range="region">
<view v-if="person.province" class="inp">{{person.province}},{{person.city}},{{person.area}}</view>
<view v-else class="inp pla">请选择地区</view>
</picker>
</view>
</view>
</view>
</template>
<script>
import provinceData from '../../static/region.json';
export default {
data() {
return {
// 省市区选择器
region: [
[],
[],
[],
],
regionIndex: [0, 0, 0],
person: {
"province": null,
"city": null,
"area": null,
},
}
},
onLoad() {
console.log(provinceData)
provinceData.forEach((item,index) =>{
this.region[0] = [...this.region[0],item.name]
})
provinceData[0].children.forEach(item =>{
this.region[1] = [...this.region[1],item.name]
})
provinceData[0].children[0].children.forEach(item =>{
this.region[2] = [...this.region[2],item.name]
})
},
methods: {
okReginon(e){
console.log(e.detail.value)
this.regionIndex = e.detail.value
this.person.province = this.region[0][this.regionIndex[0]]
this.person.city = this.region[1][this.regionIndex[1]]
this.person.area = this.region[2][this.regionIndex[2]]
},
bindMultiPickerColumnChange: function(e) {
console.log('修改的列为:' + e.detail.column + ',值为:' + e.detail.value)
console.log(this.region[e.detail.column][e.detail.value])
// 省
if(e.detail.column == 0){
this.regionIndex[0] = e.detail.value
this.region[1] = []
this.region[2] = []
provinceData[e.detail.value].children.forEach(item =>{
this.region[1] = [...this.region[1],item.name]
})
provinceData[this.regionIndex[0]].children[0].children.forEach(item =>{
this.region[2] = [...this.region[2],item.name]
})
}
// 市
else if(e.detail.column == 1){
console.log(this.regionIndex[0])
this.regionIndex[1] = e.detail.value
this.region[2] = []
provinceData[this.regionIndex[0]].children[e.detail.value].children.forEach(item =>{
this.region[2] = [...this.region[2],item.name]
})
}else{
this.regionIndex[2] = e.detail.value
}
this.$forceUpdate()
},
}
}
</script>