// utils.ts export interface Configs { command: string output: string } export interface Device { id: number device_type: string device_ip: string device_address: string device_backup_time: string device_brand: string device_hostname: string device_serial_number: string device_configs?: Configs[] } export class IDevice implements Device { //定義 interface Device 的默認實現類,用於設置默認值 id: number = 1 device_type: string = '' device_ip: string = '' device_address: string = '' device_backup_time: string = '' device_brand: string = '' device_hostname: string = '' device_serial_number: string = '' device_configs?: Configs[] }
在其他.vue文件中導入interface
// detail.vue import { ref, reactive } from 'vue' import { IDevice, Device } from './utils' // 正確用法 const d = reactive<Device>(new IDevice()) d.device_address = 'xxxxxxxxxx' // 但是以下用法vue3還不支持,已經提issue,期待解決 // defineProps不支持使用外部導入的類型,會報錯: // Internal server error: [@vue/compiler-sfc] type argument passed to defineProps() must be a literal type, or a reference to an // interface or literal type. const s = withDefaults(defineProps<Device>(), { device_address: 'ddddddddd', })
解決辦法:
在ts中我們還可以直接通過類型聲明定義props或emits,直接在defineProps方法泛型傳入類型就聲明,defineEmits也是同理,下面用項目中的一個例子 <script setup> const props = defineProps<{ handle: "add" | "update" parentId: number | null flag: boolean isDir: boolean }>() </script> 或者 如果props需要使用默認值就得用withDefaultsapi,下面是官方的例子 interface Props { msg?: string labels?: string[] } const props = withDefaults(defineProps<Props>(), { msg: 'hello', labels: () => ['one', 'two'] })
參考鏈接:https://juejin.cn/post/7015587671019880478
