视频加载失败

Vue 组件属性 Props

382 字
2 分钟
Vue 组件属性 Props

在 Vue 组件中,属性(Props)用于在父组件和子组件之间传递数据。以下是 Vue 组件属性的关键概念:

1. 基础使用#

子组件模板(单文件组件的 <template> 块):

<template>
<div>
<p>Message: {{ message }}</p>
</div>
</template>

对应的脚本(Options API):

export default {
props: ["message"], // 简单定义 props
};

父组件使用:

<ChildComponent message="Hello Vue!"/>

2. 类型验证#

Vue 允许为 props 指定数据类型:

props: {
message: String,
count: Number,
isActive: Boolean,
items: Array,
user: Object,
callback: Function
}

3. 默认值#

如果父组件未传递 prop,可以提供默认值:

props: {
count: {
type: Number,
default: 0
}
}

4. 必填#

如果某个 prop 必须提供:

props: {
title: {
type: String,
required: true
}
}

5. 自定义验证#

props: {
rating: {
type: Number,
validator: value => value >= 0 && value <= 5
}
}

6. 动态绑定#

<ChildComponent :message="parentMessage" :count="42"/>

:message 表示 message 由父组件的数据 parentMessage 绑定,而不是字符串。


7. 非 Prop Attribute#

如果子组件没有声明某个 prop,Vue 会把它当作普通 HTML 特性传递:

<ChildComponent class="custom-style"/>

如果 ChildComponent 没有 props: ["class"],这个 class 会应用到子组件的根元素。


8. 单向数据流#

Prop 只能在子组件内部 读取,不能修改。如果要修改,推荐使用:

  • 局部数据拷贝:

    props: ["count"],
    data() {
    return { localCount: this.count };
    }
  • $emit 事件通知父组件:

    <button @click="$emit('update-count', count + 1)">Increase</button>

9. 使用 defineProps(Vue 3 Composition API)#

单文件组件 <script setup> 块中:

defineProps({
message: String,
count: Number
});

Vue 组件的属性机制可以帮助父子组件高效通信,同时保持组件的封装性和可复用性。

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Vue 组件属性 Props
https://blog.81vm3.xyz/posts/vue-component-props/
作者
Blume
发布于
2024-04-15
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Blume
I build interesting things.
公告
欢迎来到我的博客!
分类
标签
最新动态
站点统计
文章
38
分类
5
标签
98
总字数
23,078
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Local
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录