之前写了一篇前后端一起搞的地址选择。但是觉得每次滑动的时候都调用好几次接口很浪费,所以决定前端自己搞吧。
首先需要一份地址源啊,后端一次性返给我们或者本地存一份(在static下)
<template>
<div class="addressFour">
<mt-picker :slots="addressSlots" @change="onAddressChange" :visible-item-count="5"v-show="valSelect==1"></mt-picker>
<mt-picker :slots="streetSlots" ref="picker" @change="onStreetChange"
:visible-item-count="5" v-show="valSelect==2" ></mt-picker>
</template>
<script>import address from
'../static/addressFour.json';
export default{name: 'addressFour', props: ['valSelect'], data () { return { popupVisible: false,//省市区三级 popupVisible2: false,//街道 streetRender:true,//街道是否展示 addressSlots: [ { flex: 1, defaultIndex: 1, values: Object.keys(address), className: 'slot1', textAlign: 'center' }, { divider: true, content: '-', className: 'slot2' }, { flex: 1, values: [], className: 'slot3', textAlign: 'center' }, { divider: true, content: '-', className: 'slot4' }, { flex: 1, values: [], className: 'slot5', textAlign: 'center' } ], streetSlots: [ { flex: 1, values: [], className: 'slot1', textAlign: 'center' } ], addressProvince: '省', addressCity: '市', county: '区', addressStreet: '街道', } }, methods: { onAddressChange(picker, values) { let shi = Object.keys(address[values[0]]); let index = shi.indexOf(values[1]) let xian = address[values[0]][shi[index]]; this.xianObj = xian; picker.setSlotValues(1, shi); this.addressProvince = values[0]; this.addressCity = values[1]; if (values[2]) {//有时为undefined this.county = values[2]; } this.$emit('addressProvince', values[0]); this.$emit('addressCity', values[1]); this.$emit('county', values[2]); let address_full = picker.getValues(); if (address_full[address_full.length - 1] != undefined) {//会出现四组值,一组有效 this.$emit('addressFull', picker.getValues()); } if (xian) {//xian报undefined,报错 picker.setSlotValues(2, Object.keys(xian)); } }, onStreetChange(picker, values){ this.addressStreet = values[0]; this.$emit('addressStreet', values[0]); }, }, watch: { 'county': { handler(val, oval){ let street = this.xianObj[val]; if(street.length===0){ this.streetRender=false; this.$emit('noPopup',false); return; } this.streetRender=true; this.streetSlots[0].values = street; }, } }, mounted(){ this.$nextTick(() => { setTimeout(() => { this.addressSlots[0].defaultIndex = 0; }, 100); }); }
}
</script>
一些参数说明:
- addressFour.json:这个是四级地址库,网上随意搞一个比较全的就好。
- valSelect这个参数控制三级地址还是街道展示
- noPopup:是否有四级(直辖市有的只有三级)
- Object.keys这个方法w3c也有,可以去看看
至此,地址三级和四级就都可以用了,三级只需valSelect置为1即可
父组件引用很简单,每个人使用方式也不同,就不列举了
本文借鉴:https://www.cnblogs.com/cools...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。