VUE+elementUI+高德API 实现省市区三级联动
通常三级联动的数据,是由自家后台返回,但时间一长的话,地方新增区域需要实时的去更新,为了避免更新缓慢,就直接使用高德地图的API来写三级联动。效果图如下:
话不多说,我后直接贴代码了。
首先在main.js引入vue-amap组件
import AMap from 'vue-amap' // 引入vue-amap
Vue.use(AMap)
// 初始化vue-amap
AMap.initAMapApiLoader({
// 申请的高德key
key: '您申请的key值&plugin=AMap.Geocoder',
// 插件集合
plugin: ['']
})
在页面使用element的cascader组件
<template>
<div>
<el-cascader
style="width:200px"
:props="props"
v-model="region"
ref="region"
clearable
></el-cascader>
</div>
</template>
<script>
export default {
data() {
return {
region: [],
districtSearch:null,
props: {
checkStrictly: true,
lazy: true,
lazyLoad: (node, resolve) => {
const label = node.label ? node.label : "中国";
let level = node.level;
this.districtSearch.search(label, function(status, result) {
let list = result.districtList[0]["districtList"];
let arr = [];
for (let i = 0; i < list.length; i++) {
arr.push({
label: list[i].name,
value: list[i].adcode,
leaf: level >= 2,
});
}
setTimeout(() => {
resolve(arr);
}, 200);
});
},
},
};
},
created() {
this.initData();
},
methods: {
initData() {
let _this = this;
AMap.plugin("AMap.DistrictSearch", function() {
_this.districtSearch = new AMap.DistrictSearch({
subdistrict: 1,
});
});
},
},
};
</script>
这就是以上的代码。
最后我说下bug点
- 在当前页面刷新是会报错vue@2.6.11:6 ReferenceError: AMap is not defined。
- 在高德API里返回的数据,我这里取的是adcode,但是在个别选择里,adcode是重复的。
如果有大佬找到解决的方法,希望能告知一下
在VUE使用的是vue-amap,而直接引入cdn就可以解决bug1,首先,在public下的index.html引入
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
//注意下,这里你申请的KEY是web端还是web服务
然后在vue.config.js中module.exports下的externals加上’AMap’: ‘AMap’,
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter',
'moment': 'moment',
'axios': 'axios',
'AMap': 'AMap'
// 'element-ui': 'ELEMENT'
},
最后需要在当如页面加上import AMap from 'AMap';
就能解决问题