欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue組件如何設(shè)置Props實(shí)例詳解

 更新時(shí)間:2022年06月09日 16:44:15   作者:天行無(wú)忌  
props主要用于組件的傳值,他的工作就是為了接收外面?zhèn)鬟^(guò)來(lái)的數(shù)據(jù),與data、el、ref是一個(gè)級(jí)別的配置項(xiàng),下面這篇文章主要給大家介紹了關(guān)于Vue組件如何設(shè)置Props的相關(guān)資料,需要的朋友可以參考下

在 Vue 中構(gòu)建組件通常需要定義一些屬性,以使組件可以更好復(fù)用,在這種情況下會(huì)使用 props 來(lái)自定義數(shù)據(jù)來(lái)傳遞數(shù)據(jù)。接下來(lái)以一個(gè)簡(jiǎn)單的組件來(lái)介紹如何使用組件 props 。

<CrayonAlert title="友情提示"  description="請(qǐng)輸入真實(shí)的信息" />

如上面代碼所示,組件定義兩個(gè)屬性 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

屬性默認(rèn)值

在上面代碼中,當(dāng)組件沒(méi)有傳入相應(yīng)的屬性值的情況下,會(huì)顯示 undefined 或者在模板HTML沒(méi)有任何文本,這個(gè)時(shí)候可以考慮定義一個(gè)默認(rèn)值:

export default {
    name: "CrayonAlert",
    props: {
        title: {
            type: String,
            default: "提示",
        },
        description: {
            type: String,
            default: "描述",
        },
    },
};

設(shè)置好默認(rèn)值后,在沒(méi)有傳入任何參數(shù)值的時(shí)候,會(huì)顯示默認(rèn)值。這種方式在 Vue2 比較常用。

屬性值驗(yàn)證

跟 Form 數(shù)據(jù)一樣,組件屬性值也可以對(duì)其進(jìn)行驗(yàn)證,如下:

export default {
    name: "CrayonAlert",
    props: {
        title: {
            type: String,
            validator(value) {
                return value !== "";
            },
        },
        description: {
            type: String,
            validator(value) {
                return value !== "";
            },
        },
    },
};

Composition API 中設(shè)置屬性

在 Vue3 中,引入了一種稱為 Composition API 的新方法。在 Composition API 中,定義 props 使用 defineProps 函數(shù)。定義沒(méi)有默認(rèn)值的屬性如下所示:

import { defineProps } from "vue";

const props = defineProps({
    title: {
        type: String,
    },
    description: {
        type: String,
    },
});

設(shè)置默認(rèn)值和在Vue2 中有點(diǎn)類似,如下:

import { defineProps } from "vue";

const props = defineProps({
    title: {
        type: String,
        default: "提示",
    },
    description: {
        type: String,
        default: "描述",
    },
});

為了避免在屬性上設(shè)置默認(rèn)值,可以通過(guò)使用 required 字段來(lái)設(shè)置屬性為必須項(xiàng)。定義代碼如下:

import { defineProps } from "vue";

const props = defineProps({
    title: {
        type: String,
        default: "提示",
        required: true,
    },
    description: {
        type: String,
        default: "描述",
        required: true,
    },
});

總結(jié)

到此這篇關(guān)于Vue組件如何設(shè)置Propsx的文章就介紹到這了,更多相關(guān)Vue組件Propsx內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論