long
2021-09-13 5f052d4e17b53d4fe07a87d53a9c112bff3dc852
提交 | 用户 | age
ad3cc5 1 /**
L 2  * 地址数据&方法
3  */
4
5 import area from './data.js' // 引入地区数组
6 // import Req from '../http_install.js' // 引入请求方法
7 const axios = require('axios')
8
9 /**
10  * 根据省名称获取城市数组
11  * @param {string} province 省名
12  * @return {object[]} 城市数组
13  */
14 function getCitiesByLabel(province) {
15   province = area.find(obj => province === obj.label)
16   return province ? province.children : []
17 }
18
19 /**
20  * 根据省市名称获取区数组
21  * @param {string} province 省名
22  * @param {string} city 城市名
23  * @return {object[]} 区数组
24  */
25 function getDistrictsByLabel(province, city) {
26   var cities = getCitiesByLabel(province)
27   city = cities.find(obj => city === obj.label)
28   return city ? city.children : []
29 }
30
31 /**
32  * 根据省市区获取区数据
33  * @param {string} province 省名
34  * @param {string} city 城市名
35  * @param {string} district 区名
36  * @return {object} 区对象数据
37  */
38 function getDistrictsObjByLabel(province, city, district) {
39   return getDistrictsByLabel(province, city).find(obj => obj.label === district)
40 }
41
42 /**
43  * 初始化 elementUI Cascader 的 option
44  * @param {object[]} areaArr 地区数据
45  * @return {object[]} elementUI 级联选择组件用的 option 参数
46  */
47 function getAreaOpts(areaArr) {
48   if (!areaArr || !areaArr.length) {
49     return
50   }
51   return areaArr.map((obj) => {
52     return {
53       value: obj.label,
54       label: obj.label,
55       code: obj.value,
56       children: getAreaOpts(obj.children)
57     }
58   })
59 }
60
61 /**
62  * 请求获取街道json数据 - 根据传入的区编号,请求对应的json文件
63  * Promise
64  * @param {string} districtCode 区编号
65  * @param {VueObject} _this vue页面实例
66  * @resolve {'街道号': '街道名', ...}
67  */
68 function getStreetByDistrictCode(districtCode) {
69   return new Promise((resolve, reject) => {
70     if (!districtCode) {
71       reject('缺失 districtCode')
72     }
73     // TODO 改为axios
74     axios({
75       method: 'GET',
76       url: './static/town/' + districtCode + '.json',
77       header: {
78         'content-type': 'application/json' // 默认值
79       }
80     }).then((res) => {
81       const result = []
82       const data = res.data
83       // 构建街道数组
84       // 注:此处label与value一致,预留一个code字段保留街道编号
85       if (data) {
86         for (var i in data) {
87           result.push({
88             label: data[i],
89             value: data[i],
90             code: i
91           })
92         }
93       }
94       resolve(result)
95     }).catch(() => {
96       reject()
97     })
98   })
99 }
100
101 export default {
102   data: area, getAreaOpts,
103
104   getCitiesByLabel,
105   getDistrictsByLabel,
106   getDistrictsObjByLabel,
107   getStreetByDistrictCode
108 }