index.vue 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <!-- 省市区选择组件 -->
  2. <template>
  3. <el-cascader
  4. clearable
  5. :value="value"
  6. :options="regionsData"
  7. :placeholder="placeholder"
  8. popper-class="ele-pop-wrap-higher"
  9. :props="props"
  10. @input="updateValue"
  11. />
  12. </template>
  13. <script>
  14. import { getRegionsData } from './load-data';
  15. export default {
  16. name: 'RegionsSelect',
  17. props: {
  18. value: [Array, String, Number],
  19. placeholder: String,
  20. options: Array,
  21. valueField: {
  22. type: String,
  23. validator: (val) => {
  24. return !val || val === 'label';
  25. }
  26. },
  27. type: {
  28. type: String,
  29. validator: (type) => {
  30. return !type || ['provinceCity', 'province'].includes(type);
  31. }
  32. },
  33. props: Object
  34. },
  35. data() {
  36. return {
  37. // 级联选择器数据
  38. regionsData: []
  39. };
  40. },
  41. methods: {
  42. /* 更新 value */
  43. updateValue(value) {
  44. this.$emit('input', value);
  45. },
  46. /* 级联选择器数据 value 处理 */
  47. formatData(data) {
  48. if (this.valueField === 'label') {
  49. return data.map((d) => {
  50. const item = {
  51. label: d.label,
  52. value: d.label
  53. };
  54. if (d.children) {
  55. item.children = d.children.map((c) => {
  56. const cItem = {
  57. label: c.label,
  58. value: c.label
  59. };
  60. if (c.children) {
  61. cItem.children = c.children.map((cc) => {
  62. return {
  63. label: cc.label,
  64. value: cc.label
  65. };
  66. });
  67. }
  68. return cItem;
  69. });
  70. }
  71. return item;
  72. });
  73. } else {
  74. return data;
  75. }
  76. },
  77. /* 省市区数据筛选 */
  78. filterData(data) {
  79. if (this.type === 'provinceCity') {
  80. return this.formatData(
  81. data.map((d) => {
  82. const item = {
  83. label: d.label,
  84. value: d.value
  85. };
  86. if (d.children) {
  87. item.children = d.children.map((c) => {
  88. return {
  89. label: c.label,
  90. value: c.value
  91. };
  92. });
  93. }
  94. return item;
  95. })
  96. );
  97. } else if (this.type === 'province') {
  98. return this.formatData(
  99. data.map((d) => {
  100. return {
  101. label: d.label,
  102. value: d.value
  103. };
  104. })
  105. );
  106. } else {
  107. return this.formatData(data);
  108. }
  109. }
  110. },
  111. watch: {
  112. options: {
  113. handler(options) {
  114. this.regionsData = this.filterData(options ?? []);
  115. if (!options) {
  116. getRegionsData().then((data) => {
  117. this.regionsData = this.filterData(data ?? []);
  118. this.$emit('load-data-done', data);
  119. });
  120. }
  121. },
  122. immediate: true
  123. }
  124. }
  125. };
  126. </script>