github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/static_source/admin/src/views/Entities/components/EntityAction.vue (about) 1 <script setup lang="ts"> 2 3 import {PropType, ref, unref, watch} from "vue"; 4 import {ApiEntity} from "@/api/stub"; 5 import {ElAutocomplete} from 'element-plus' 6 import api from "@/api/api"; 7 8 const currentEntity = ref<Nullable<ApiEntity>>(null) 9 const entityId = ref<Nullable<string>>(null) 10 const emit = defineEmits(['change', 'update:modelValue']) 11 12 const props = defineProps({ 13 modelValue: { 14 type: Object as PropType<Nullable<ApiEntity>>, 15 default: () => undefined 16 } 17 }) 18 19 watch( 20 () => props.modelValue, 21 (val?: ApiEntity) => { 22 if (val === unref(currentEntity)) return 23 entityId.value = val?.id || null; 24 currentEntity.value = val || null; 25 }, 26 27 ) 28 29 // 监听 30 watch( 31 () => currentEntity.value, 32 (val?: ApiEntity) => { 33 emit('update:modelValue', val) 34 if (!val) { 35 emit('change', val) 36 } 37 }, 38 { 39 immediate: true 40 } 41 ) 42 43 const querySearchAsync = async (queryString: string, cb: Fn) => { 44 if (queryString == null || queryString == 'null') { 45 queryString = '' 46 } 47 const params = {query: queryString, limit: 25, offset: 0} 48 const {data} = await api.v1.entityServiceSearchEntity(params) 49 const {items} = data 50 cb(items) 51 } 52 53 const handleChange = (val) => { 54 if (val == '') { 55 currentEntity.value = null 56 } 57 } 58 const handleSelect = (val: ApiEntity) => { 59 currentEntity.value = val 60 emit('change', val) 61 } 62 63 </script> 64 65 <template> 66 <ElAutocomplete 67 class="w-[100%]" 68 v-model="entityId" 69 :fetch-suggestions="querySearchAsync" 70 placeholder="Please input" 71 value-key="id" 72 @select="handleSelect" 73 @change="handleChange" 74 /> 75 </template> 76 77 <style lang="less"> 78 79 </style>