您的位置:首页 > 文旅 > 旅游 > 大连百度推广公司有几家_企业文化培训_优化营商环境条例解读_如何做一个自己的网页

大连百度推广公司有几家_企业文化培训_优化营商环境条例解读_如何做一个自己的网页

2025/3/31 18:34:24 来源:https://blog.csdn.net/Vae2437426397/article/details/146497205  浏览:    关键词:大连百度推广公司有几家_企业文化培训_优化营商环境条例解读_如何做一个自己的网页
大连百度推广公司有几家_企业文化培训_优化营商环境条例解读_如何做一个自己的网页

一、基本该概念

Props 是父组件向子组件传递数据的桥梁,子组件通过定义 props 接收父组件的数据

二、定义方式

1、简单类型定义(数组形式)

// 子组件定义
props: ['name', 'age']// 父组件使用
<child-component :name="userName" :age="userAge" />

2、对象类型定义(推荐)

props: {name: {type: String,default: 'Guest',required: true},age: {type: Number,validator: (value) => value >= 0}
}

三、类型验证

支持的类型:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

四、默认值设置

// 基础类型默认值
age: {type: Number,default: 0
}// 对象/数组默认值(需通过工厂函数返回)
userInfo: {type: Object,default: () => ({ name: 'Guest' })
}

五、必传验证 

name: {type: String,required: true
}

六、自定义验证 

email: {type: String,validator: (val) => {const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/return emailRegex.test(val)}
}

 七、使用场景

1、动态数据绑定

<child-component :count="currentCount" />

2、单向数据流

  • 子组件不能直接修改 props
  • 需通过 $emit 触发父组件方法更新

3、接收任意类型

content: null // 不指定类型,接收任意类型

八、注意事项 

1、驼峰命名转换

// 子组件定义
props: { myProp: String }// 父组件使用(HTML标签需转为短横线命名)
<child-component my-prop="value" />

2、数组/对象解构 

// 子组件使用解构
const { name, age } = props

3、监听props变化

watch: {propsData: {handler(newVal, oldVal) {// 处理变化},deep: true}
}

 九、最佳实践

  1. props 命名建议使用驼峰式
  2. 复杂对象使用对象形式定义
  3. 始终设置合理的默认值
  4. 必要时添加类型验证和自定义校验
  5. 避免在子组件直接修改 props 值

示例代码:

父组件:

<template><user-card :user-info="user" :is-vip="isMember"@update:user-info="handleUpdate"/>
</template><script>
import UserCard from '@/components/UserCard.vue'export default {components: { UserCard },data() {return {user: { name: 'John', age: 30 },isMember: true}},methods: {handleUpdate(newUser) {this.user = newUser}}
}
</script>

子组件:

<template><view class="card"><text>{{ userInfo.name }}</text><text v-if="isVip">VIP Member</text></view>
</template><script>
export default {props: {userInfo: {type: Object,required: true,default: () => ({})},isVip: {type: Boolean,default: false}}
}
</script>

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com