目录属性类型属性默认值属性值验证Composition api 中设置属性总结在 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 ,还可以是以下类型:
在上面代码中,当组件没有传入相应的属性值的情况下,会显示 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 !== "";
},
},
},
};
在 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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Vue组件如何设置Props实例详解
本文链接: https://www.lsjlt.com/news/151016.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0