ts从单独的ts文件中导出interface

// 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

 

posted @ 2022-02-12 18:10  明天OoO你好  阅读(4577)  评论(0编辑  收藏  举报