Wechat search [Great Relocation to the World], I will share with you the front-end industry trends, learning methods, etc. as soon as possible.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
Vue requires that any data passed to a component must be declared as props
. Additionally, it provides a powerful built-in mechanism to validate this data. This is like a contract between a component and a consumer, ensuring that the component is used as intended.
In this lesson, let's take a look at this verification mechanism, which can help us reduce but and increase our self-confidence (fishing time) during development and debugging.
Base
primitive type
It is relatively simple to verify the basic type, we will not introduce too much here, just look at the following example:
export default {
props: {
// Basic type check
// ("null "和 "undefined "值允许任何类型)
propA: Number,
// 多种可能的类型
propB: [String, Number],
// 必传的参数
propC: {
type: String,
required: true
},
// 默认值
propD: {
type: Number,
default: 100
},
}
}
complex type
Complex types can also be validated in the same way.
export default {
props: {
// 默认值的对象
propE: {
type: Object,
// 对象或数组的默认值必须从
// 一个工厂函数返回。该函数接收原始
// 元素作为参数。
default(rawProps) {
return { message: 'hello' }
}
},
// 数组默认值
propF: {
type: Array,
default() {
return []
}
},
// 函数默认值
propG: {
type: Function,
// 不像对象或数组的默认值。
// 这不是一个工厂函数
// - 这是一个作为默认值的函数
default() {
return 'Default function'
}
}
}
}
type
can be one of the following:
- Number
- String
- Boolean
- Array
- Object
- Date
- Function
- Symbol
Also, type
can also be a custom class or constructor, then use instanceof
to check. For example, given the following class:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
We can pass Person
as a type to prop
type:
export default {
props: {
author: Person
}
}
Advanced verification
validator method
Props supports the use of a validator
function. This function accepts the prop raw value and must return a boolean value to determine if the prop is valid.
prop: {
validator(value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
}
}
use enumeration
Sometimes we want to narrow down the values to a specific set, which can be achieved by enumeration:
export const Position = Object.freeze({
TOP: "top",
RIGHT: "right",
BOTTOM: "bottom",
LEFT: "left"
});
It can be imported for use in validator
or as a default:
<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>
Finally, parent components can also import and use this enum, which eliminates the use of magic strings in our application:
<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>
boolean map
Boolean classes have unique behavior. The presence or absence of a property can determine the value of the prop.
<!-- 等价于 :disabled="true" -->
<MyComponent disabled />
<!-- 价于 :disabled="false" -->
<MyComponent />
TypeScript
Combining Vue's built-in prop validation with TypeScript gives us more control over this mechanism, since TypeScript supports interfaces and enums natively.
Interface
We can annotate complex prop types with an interface and PropType
. This ensures that the passed object will have a specific structure.
<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>
enumerate
We've already explored how to fake an enum in JS. This is not needed for TypeScript, which supports it natively:
<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>
vue3
All of the above are valid when using Vue 3 with options API or composition API. The difference is when using <script setup>
. props must be declared using the defineProps()
macro as follows:
<script setup>
const props = defineProps(['foo'])
console.log(props.foo)
</script>
<script setup>
defineProps({
title: String,
likes: Number
})
</script>
Or when using TypeScript's <script setup>
, you can declare props using pure type annotations:
<script setup lang="ts">
defineProps<{
title?: string
likes?: number
}>()
</script>
Or use an interface:
<script setup lang="ts">
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()
</script>
Finally, when using type-based declarations, declare default values.
<script setup lang="ts">
interface Props {
foo: string
bar?: number
}
const { foo, bar = 100 } = defineProps<Props>()
</script>
The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool , Fundebug .
Summarize
Author: Fotis Adamakis Translator: Front-end Xiaozhi Source: mediun
Original: https://fadamakis.mdium.com/validating-yur-vue-props-like-a-pro-5a2d0ed2b2d6
comminicate
If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。