ElementPlus裏的類型別名聲明及使用

前言

最近剛開始使用ts,定義的變量總是不知道類型,特別是第三方庫中,更是不知道有哪些類型,笨人本辦法,遇到一個就記錄一下,方便我下次使用查詢

組件實例

我們通過組件的ref屬性獲取組件實例時,定義的實例變量需要指定類型。下面是常見的一些組件實例類型

el-scrollbar

<template>
  <el-scrollbar ref="scrollbarRef"></el-scrollbar>
</template>

<script lang="ts" setup>
  import type { ElScrollbar } from 'element-plus';
  const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
  scrollbarRef.value!.setScrollTop(value)
</script>

el-form

<template>
  <el-form ref="ruleFormRef"></el-form>
</template>

<script lang="ts" setup>
  import type { ElForm } from 'element-plus';
  // 可以單獨定義一個類型
  type FormInstance = InstanceType<typeof ElForm>;
  const ruleFormRef = ref<FormInstance>();
  ruleFormRef.value!.resetFields();
</script>

el-table

<template>
  <el-table ref="multipleTable"></el-table>
</template>

<script lang="ts" setup>
  import type { ElTable } from "element-plus";
  const multipleTable = ref<InstanceType<typeof ElTable>>();
  multipleTable.value!.clearSelection();
</script>

el-input

<template>
  <el-input ref="multipleTable" v-model="value"></el-table>
</template>

<script lang="ts" setup>
  import type { ElInput } from "element-plus";
  const multipleTable = ref<InstanceType<typeof ElInput>>();
  multipleTable.value!.focus()
</script>

Props 屬性類型

當我們要動態設置某些組件的props屬性時,有些屬性也是有類型的,如果定義不對,也是會有ts類型錯誤提示的。

組件的 size 屬性

ComponentSize
export declare const componentSizes: readonly ["", "default", "small", "large"];

// template
<el-table ref="multipleTable" :size="tableSize"></el-table>

// ts
import type { ComponentSize } from 'element-plus';
const tableSize = ref<ComponentSize>('default');

時間組件的類型

DatePickType
export declare const datePickTypes: readonly ["year", "month", "date", "dates", "week", "datetime", "datetimerange", "daterange", "monthrange"];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章