像專業(yè)人員一樣驗(yàn)證你的Vue Props
Vue 要求將傳遞給組件的任何數(shù)據(jù)顯式聲明為 props。此外,它還提供了一個(gè)強(qiáng)大的內(nèi)置機(jī)制來驗(yàn)證這些數(shù)據(jù)。這就像組件和消費(fèi)者之間的合同一樣,確保組件按預(yù)期使用。
讓我們來探討一下這個(gè)強(qiáng)大的工具,它可以幫助我們?cè)陂_發(fā)和調(diào)試過程中減少錯(cuò)誤并增加我們的信心。
一、基礎(chǔ)知識(shí)
1.1 原始類型
驗(yàn)證原始類型就像為原始類型構(gòu)造函數(shù)設(shè)置類型選項(xiàng)一樣簡單。
export default {
props: {
// Basic type check
// (`null` and `undefined` values will allow any type)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Number with a default value
propD: {
type: Number,
default: 100
},
}
}
1.2 復(fù)雜類型
復(fù)雜類型也可以用同樣的方式進(jìn)行驗(yàn)證。
export default {
props: {
// 具有默認(rèn)值的對(duì)象
propE: {
type: Object,
// 對(duì)象或數(shù)組默認(rèn)值必須從一個(gè)工廠函數(shù)。該函數(shù)接收原始組件作為參數(shù)接收的props。
default(rawProps) {
return { message: 'hello' }
}
},
// 具有默認(rèn)值的數(shù)組
propF: {
type: Array,
default() {
return []
}
},
// 具有默認(rèn)值的函數(shù)
propG: {
type: Function,
// 與對(duì)象或數(shù)組默認(rèn)不同,這不是工廠函數(shù) - 這是一個(gè)用作默認(rèn)值的函數(shù)
default() {
return 'Default function'
}
}
}
}
類型可以是以下值之一:
- Number
- String
- Boolean
- Array
- Object
- Date
- Function
- Symbol
另外,type 也可以是自定義類或者構(gòu)造函數(shù),斷言會(huì)通過 instanceof 檢查。例如,給定以下類:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
你可以像這樣把它作為一個(gè) props 類型。
export default {
props: {
author: Person
}
}
二、高級(jí)驗(yàn)證
2.1 驗(yàn)證器函數(shù)
props 支持使用一個(gè)驗(yàn)證器函數(shù),這個(gè)函數(shù)接受 props 的原始值,并且必須返回一個(gè)布爾值來確定這個(gè) props 是否有效。
// 自定義驗(yàn)證器函數(shù)
prop: {
validator(value) {
// 該值必須與這些字符串之一匹配
return ['success', 'warning', 'danger'].includes(value)
}
},
2.2 使用枚舉
有時(shí)你想把數(shù)值縮小到一個(gè)特定的集合,這可以通過偽造這樣的枚舉來實(shí)現(xiàn):
export const Position = Object.freeze({
TOP: "top",
RIGHT: "right",
BOTTOM: "bottom",
LEFT: "left"
});
可以在驗(yàn)證器中導(dǎo)入和使用,也可以作為默認(rèn)值。
<template>
<span :class="`arrow-position--${position}`">
{{ position }}
</span>
</template>
<script>
import { Position } from "./types";
export default {
props: {
position: {
validator(value) {
return Object.values(Position).includes(value);
},
default: Position.BOTTOM,
},
},
};
</script>
最后,父組件也可以導(dǎo)入和使用這個(gè)枚舉,從而消除我們應(yīng)用程序中魔術(shù)字符串的使用。
<template>
<DropDownComponent :position="Position.BOTTOM" />
</template>
<script>
import DropDownComponent from "./components/DropDownComponent.vue";
import { Position } from "./components/types";
export default {
components: {
DropDownComponent,
},
data() {
return {
Position,
};
},
};
</script>
2.3 布爾型投射
布爾 prop 具有獨(dú)特的行為,屬性的存在與否可以決定prop值。
<!-- 相當(dāng)于通過 :disabled="true" -->
<MyComponent disabled />
<!-- 相當(dāng)于通過 :disabled="false" -->
<MyComponent />
三、TypeScript
將 Vue 的內(nèi)置 prop 驗(yàn)證與 TypeScript 相結(jié)合可以讓我們更好地控制這種機(jī)制,因?yàn)?TypeScript 原生支持接口和枚舉。
3.1 Interfaces
我們可以使用一個(gè)接口和PropType工具來注解復(fù)雜的 prop 類型,這確保了傳遞的對(duì)象將有一個(gè)特定的結(jié)構(gòu)。
<script lang="ts">
import Vue, { PropType } from 'vue'
interface Book {
title: string
author: string
year: number
}
const Component = Vue.extend({
props: {
book: {
type: Object as PropType<Book>,
required: true,
validator (book: Book) {
return !!book.title;
}
}
}
})
</script>
3.2 真實(shí)枚舉
我們已經(jīng)探索了如何在 Javascript 中偽造枚舉。這對(duì)于 TypeScript 來說是不需要的,因?yàn)槊杜e是原生支持的。
<script lang="ts">
import Vue, { PropType } from 'vue'
enum Position {
TOP = 'top',
RIGHT = 'right',
BOTTOM = 'bottom',
LEFT = 'left',
}
export default {
props: {
position: {
type: String as PropType<Position>,
default: Position.BOTTOM,
},
},
};
</script>
四、Vue 3
當(dāng)使用帶有 Options 或 Composition API 的 Vue 3 時(shí),以上所有內(nèi)容都有效。不同之處在于使用 <script setup> 時(shí)。必須使用 defineProps() 宏聲明道具,如下所示:
<script setup>
const props = defineProps(['foo'])
console.log(props.foo)
</script>
<script setup>
// 還支持長語法
defineProps({
title: String,
likes: Number
})
</script>
或者當(dāng)使用帶有 <script setup> 的 TypeScript 時(shí),可以使用純類型注釋來聲明 props:
<script setup lang="ts">
defineProps<{
title?: string
likes?: number
}>()
</script>
或使用接口:
<script setup lang="ts">
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()
</script>
最后,在使用基于類型的聲明時(shí)聲明默認(rèn)值:
<script setup lang="ts">
interface Props {
foo: string
bar?: number
}
// defineProps() 的反應(yīng)性解構(gòu)
// 默認(rèn)值被編譯為等效的運(yùn)行時(shí)選項(xiàng)ime option
const { foo, bar = 100 } = defineProps<Props>()
</script>
結(jié)束
隨著你的應(yīng)用程序規(guī)模的擴(kuò)大,類型檢查是防止錯(cuò)誤的第一道防線。Vue的內(nèi)置prop 驗(yàn)證是引人注目的。結(jié)合TypeScript,它可以讓你對(duì)正確使用組件接口有很高的信心,減少bug,提高整體代碼質(zhì)量和開發(fā)體驗(yàn)。
原文:https://fadamakis.medium.com/validating-your-vue-props-like-a-pro-5a2d0ed2b2d6作者:Fotis Adamakis