最近项目上线部署完毕闲着没事, 感觉mint-ui里面的picker组件和自己的需求有冲突,所以就基于它自己封装了一个省市联动组件!
1:父组件调用子组件的地方
注册组件什么的就不说了
<mt-button type="primary" size="small" @click="getcode()">选择地址</mt-button>
地址是:{{Provin}} --- {{city}}
<Pockers
:Province="Province" ref="Pocker"
v-on:childByValue="childByValue">
</Pockers>
Province //传给组件的json数据
v-on:childByValue //获取子组件返回的最终选择地址
附上methods里面的两个方法
methods:{
childByValue: function (Provin,city) {//实时监测子组件传递过来的数据
this.Provin = Provin;
this.city = city;
},
getcode(){
this.$refs.Pocker.popupVisible = true;
},
},
2:子组件代码 Picker
<template>
<div>
<mt-popup v-model="popupVisible" position="bottom" >
<mt-picker :slots="slots" @change="onValuesChange" :visibleItemCount="5" showToolbar>
<div class="picker-toolbar-title">
<div class="usi-btn-cancel" @click="popupVisible = !popupVisible">取消</div>
<div class="">请选择城市</div>
<div class="usi-btn-sure" @click="popupVisible = !popupVisible">确定</div>
</div>
</mt-picker>
</mt-popup>
</div>
</template>
<script>
export default {
props:['Province'],//父组件传递过来的组件数据
data(){
return{
popupVisible:false,//控制弹窗是否显示 这里是自下而上的方向
slots: [
{
flex: 1,
values:this.Provincelist(), //省份数组
className: 'slot1',
textAlign: 'left'
},
//分隔符
{
divider: true,
content: '--',
className: 'slot2'
},
//市
{
flex: 1,
values:this.cities('河北省'),
className: 'slot3',
textAlign: 'right'
}
],
Provin:'',//省份
city:'',//市区
}
},
methods:{
onValuesChange(picker, values) {//当滑动内容发生改变的时候
if(this.popupVisible){
picker.setSlotValues(1, this.cities(values[0]));
this.Provin = values[0]
this.city = values[1]
this.$emit('childByValue', this.Provin,this.city)//实时返回最新值给父组件
}
},
Provincelist(){//省份
let list = []
this.Province.provinces.forEach(item => {
list.push(item.provinceName)
});
return list
},
cities(provinceArray){//市区
let cityArr = []
this.Province.provinces.forEach(item =>{
if(item.provinceName === provinceArray){
item.citys.forEach(ages =>{
cityArr.push(ages.citysName)
})
}
})
return cityArr
}
},
mounted(){}
}
</script>
<style lang="less" scoped>
.mint-popup-bottom {
width:100%;
background:blanchedalmond;
}
.picker-toolbar-title {
display: flex;
flex-direction: row;
justify-content: space-around;
height: .4rem;
line-height: .4rem;
font-size: .16rem;
}
.usi-btn-cancel,
.usi-btn-sure {
color: #FF6600
}
</style>
如有不对之处,请各位大佬指正....