Vue組件如何設置Props實例詳解
在 Vue 中構建組件通常需要定義一些屬性,以使組件可以更好復用,在這種情況下會使用 props 來自定義數據來傳遞數據。接下來以一個簡單的組件來介紹如何使用組件 props 。
<CrayonAlert title="友情提示" description="請輸入真實的信息" />
如上面代碼所示,組件定義兩個屬性 title 和 description,組件代碼如下:
<template>
<div>
<h2>{{ title }}</h2>
<p>{{ description }}</p>
</div>
</template>
<script>
export default {
name: "CrayonAlert",
props: {
title: {
type: String,
},
description: {
type: String,
},
},
};
</script>屬性類型
props 不僅限于 String ,還可以是以下類型:
- Object
- Array
- Symbol
- Function
- Number
- String
- Date
- Boolean
屬性默認值
在上面代碼中,當組件沒有傳入相應的屬性值的情況下,會顯示 undefined 或者在模板HTML沒有任何文本,這個時候可以考慮定義一個默認值:
export default {
name: "CrayonAlert",
props: {
title: {
type: String,
default: "提示",
},
description: {
type: String,
default: "描述",
},
},
};設置好默認值后,在沒有傳入任何參數值的時候,會顯示默認值。這種方式在 Vue2 比較常用。
屬性值驗證
跟 Form 數據一樣,組件屬性值也可以對其進行驗證,如下:
export default {
name: "CrayonAlert",
props: {
title: {
type: String,
validator(value) {
return value !== "";
},
},
description: {
type: String,
validator(value) {
return value !== "";
},
},
},
};Composition API 中設置屬性
在 Vue3 中,引入了一種稱為 Composition API 的新方法。在 Composition API 中,定義 props 使用 defineProps 函數。定義沒有默認值的屬性如下所示:
import { defineProps } from "vue";
const props = defineProps({
title: {
type: String,
},
description: {
type: String,
},
});設置默認值和在Vue2 中有點類似,如下:
import { defineProps } from "vue";
const props = defineProps({
title: {
type: String,
default: "提示",
},
description: {
type: String,
default: "描述",
},
});為了避免在屬性上設置默認值,可以通過使用 required 字段來設置屬性為必須項。定義代碼如下:
import { defineProps } from "vue";
const props = defineProps({
title: {
type: String,
default: "提示",
required: true,
},
description: {
type: String,
default: "描述",
required: true,
},
});總結
到此這篇關于Vue組件如何設置Propsx的文章就介紹到這了,更多相關Vue組件Propsx內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3在自定義hooks中使用useRouter報錯的解決方案
這篇文章主要介紹了vue3在自定義hooks中使用useRouter報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
Vue執(zhí)行方法,方法獲取data值,設置data值,方法傳值操作
這篇文章主要介紹了Vue執(zhí)行方法,方法獲取data值,設置data值,方法傳值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

