×

Vue开发:vue里面组件设置Props

作者:abc1232022.06.10来源:Web前端之家浏览:3249评论:0
关键词:vuejs

收藏一个Vue开发小知识: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,
    },
});

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/vuejs20220610a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: