当前位置: 首页 > news >正文

uniapp中props的用法

一、基本该概念

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>

 

相关文章:

  • 3.24学习总结 Java多态+包和final关键字
  • 大文件切片上传和断点续传
  • Typora1.10破解教程
  • 数智读书笔记系列024《主数据驱动的数据治理 —— 原理、技术与实践》
  • SSM整合
  • MySQL MVCC的快照读和当前读区别,Redis的RDB+AOF混合持久化流程。
  • 用SVG绕过浏览器XSS审计
  • Axure项目实战:智慧城市APP(五)新闻资讯、就业信息(动态面板)
  • 微调0.5 B-32B模型要达到85%的准确率需要的数据和资源-会话质检和会话小结
  • 比手动备份快 Iperius全自动加密备份,NAS/云盘/磁带机全兼容
  • MagicFlow-防火墙网关-任意文件读取漏洞
  • 如何面对自己有意识和无意识的逃避(一)
  • c++R 格式
  • 超融合服务器是什么
  • python中使用openssl构建root证书,CSR,并验证
  • Go 语言 fmt 模块的完整方法详解及示例
  • 标星 62.9 万,8 个 yyds 的 GitHub 开源项目 !
  • C++中的std::move函数详解:移动语义与资源管理
  • golang结构体与指针类型
  • ARM day2
  • 机器人为啥热衷“搞体育”,经济日报:是向加速融入日常生活发起的冲锋
  • 霍步刚任辽宁沈阳市委书记
  • 一图看懂|印巴交火后,双方基地受损多少?
  • 端午假期购票日历发布,今日可购买5月29日火车票
  • 观察|本轮印巴冲突或促使印度空军寻求更先进战机
  • 日本前卫艺术先驱群展上海:当具体派相遇古树古宅