父组件通过 props 属性给子组件传递数据:
可以在组件上注册一些自定义的 attribute,父组件给 attribute 赋值,子组件通过 attribute 的名称获取对应的值。
Vue 遵循单向数据流。数据的流动是单向的,父组件传递给子组件数据,子组件只能使用而不能直接修改。
// App.vue
<template>
<!-- 1. 父组件通过属性给子组件传递数据 -->
<UserInfo name='Lee' age=18 height='1.88'/>
</template>
<script>
import UserInfo from './components/UserInfo'
export default {
components: {
UserInfo,
}
}
</script>
<style scoped>
</style>
// UserInfo.vue
<template>
<div>
<div>姓名:{
{ name }}</div>
<div>年龄:{
{ age }}</div>
<div>身高:{
{ height }}</div>
</div>
</template>
<script>
export default {
// 2. 子组件通过 props 选项接收父组件传递过来的数据
props: ['name', 'age', 'height'],
}
</script>
<style scoped>
</style>
props 的常见写法:
- 字符串数组:
export default { props: ['name', 'age', 'height'], }
- 对象:可以指定数据的默认值、类型、是否是必须的。
export default { props: { name: String, age: [String, Number], // 多个可能的类型 height: { default: 1.88, type: Number, // type 常见的类型:String、Number、Boolean、Array、Object、Date、Function、Symbol。如果类型是 Array 或者 Object,要写默认值的话,默认值必须是一个函数,函数的返回值是数组或对象;如果类型是 Function,要写默认值的话,default 直接写作一个函数即可。 required: true, } } }
props 自定义验证函数:
export default {
props: {
// 数据的值必须匹配下列数组中的一个
validator(value) {
return ['success', 'warning', 'dange