SelectCity.vue 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <template>
  2. <a-cascader
  3. v-model:value="value"
  4. :options="data"
  5. :field-names="{ label: 'text', value: useCode ? 'value' : 'text' }"
  6. :style="{ width: '100%' }"
  7. placeholder="请选择省市"
  8. @change="handleChange"
  9. />
  10. </template>
  11. <script setup lang="ts">
  12. import NotConfigue from '@/api/NotConfigue';
  13. import { onMounted, ref, computed, watch } from 'vue';
  14. const data = ref<Array<any>>([]);
  15. const localValue = ref<Array<string | number>>([]);
  16. const props = defineProps({
  17. modelValue: {
  18. type: Array as () => Array<string | number>,
  19. default: () => []
  20. },
  21. useCode: {
  22. type: Boolean,
  23. default: false,
  24. },
  25. })
  26. const emit = defineEmits(['update:modelValue'])
  27. // 计算属性用于双向绑定
  28. const value = computed({
  29. get() {
  30. return props.modelValue || localValue.value;
  31. },
  32. set(newValue) {
  33. localValue.value = newValue;
  34. emit('update:modelValue', newValue);
  35. }
  36. })
  37. // 监听外部modelValue变化
  38. watch(
  39. () => props.modelValue,
  40. (newValue) => {
  41. if (newValue && JSON.stringify(newValue) !== JSON.stringify(localValue.value)) {
  42. localValue.value = [...newValue];
  43. }
  44. },
  45. { deep: true }
  46. )
  47. onMounted(() => {
  48. NotConfigue.get('https://mn.wenlvti.net/app_static/xiangan/city-data.json', '', undefined).then((res) => {
  49. data.value = res.data as any[];
  50. // 如果有初始值,设置到本地状态
  51. if (props.modelValue && props.modelValue.length > 0) {
  52. localValue.value = [...props.modelValue];
  53. }
  54. })
  55. });
  56. function handleChange(values: Array<string | number>) {
  57. emit('update:modelValue', values);
  58. }
  59. </script>