Region.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import * as Api from '@/api/region'
  2. import storage from '@/utils/storage'
  3. import regionData from '../data/region'
  4. const REGION_TREE = 'region_tree'
  5. /**
  6. * 商品分类 model类
  7. * RegionModel
  8. */
  9. export default {
  10. // 从服务端获取全部地区数据(树状)
  11. getTreeDataFromApi() {
  12. return new Promise((resolve, reject) => {
  13. Api.tree().then(result => resolve(result.data.list))
  14. })
  15. },
  16. // 获取所有地区(树状) 从storage中获取
  17. getTreeData() {
  18. return new Promise((resolve, reject) => {
  19. // 判断缓存中是否存在
  20. const data = storage.get(REGION_TREE)
  21. // 从服务端获取全部地区数据
  22. if (data) {
  23. resolve(data)
  24. } else {
  25. this.getTreeDataFromApi().then(list => {
  26. // 缓存24小时
  27. storage.set(REGION_TREE, list, 24 * 60 * 60)
  28. resolve(list)
  29. })
  30. }
  31. })
  32. },
  33. // 同步获取所有地区(树状)
  34. getTreeDataSync() {
  35. return regionData
  36. },
  37. // 获取所有地区的总数
  38. getCitysCount() {
  39. return new Promise((resolve, reject) => {
  40. // 获取所有地区(树状)
  41. this.getTreeData().then(data => {
  42. const cityIds = []
  43. // 遍历省份
  44. for (const pidx in data) {
  45. const province = data[pidx]
  46. // 遍历城市
  47. for (const cidx in province.city) {
  48. const cityItem = province.city[cidx]
  49. cityIds.push(cityItem.id)
  50. }
  51. }
  52. resolve(cityIds.length)
  53. })
  54. })
  55. },
  56. // 同步获取所有地区的总数
  57. getCitysCountSync() {
  58. const regionData = this.getTreeDataSync()
  59. const cityIds = []
  60. for (const pidx in regionData) {
  61. const province = regionData[pidx]
  62. for (const cidx in province.city) {
  63. const cityItem = province.city[cidx]
  64. cityIds.push(cityItem.id)
  65. }
  66. }
  67. return cityIds.length
  68. }
  69. }