本组件

<template>
	<view>
		
		<user-name username="熏悟空"></user-name>
		<user-name username="猪八戒"></user-name>
		
	</view>
</template>

<script setup>  

	
	
</script>

<style lang="scss" >

</style>

自定义组件

<template>
	<view class="box">
		<image src="/static/1.jpeg" mode="" class="avat"></image>
		<view class="username">{{username}}</view>
		
	</view>
</template>

<script setup>
	defineProps(['username','avat'])
</script>

<style lang="scss" scoped>
	//scoped 只限于组件内部
	.box{
		width: 100%;
		height: 200px;
		background: #ccc;
		display: flex;
		align-items: center;     //左右居中
		justify-content: center;  //上下居中
		flex-direction: column; //主轴变为垂直方向‌:子元素按顺序垂直堆叠
		image{
			width: 120px;
			height: 120px;
			border-radius: 50%; //圆角
		}
		.uname{
			padding: 10px 0; 
			font-size: 20px;  //大小
		}
	}
</style>

------------------------------defineProps ---------------------------

vue3 defineProps 基本用法

defineProps 是 Vue 3 组合式 API 中用于声明组件 props 的编译器宏。它在 <script setup> 语法糖中自动可用,无需显式导入。

<script setup>
const props = defineProps({
  title: String,
  likes: Number
})
</script>

类型声明方式

支持两种声明方式:运行时声明和类型声明。类型声明在 TypeScript 项目中更推荐使用。

运行时声明:

defineProps({
  message: String,
  count: {
    type: Number,
    required: true,
    default: 0
  }
})

TypeScript 类型声明:

defineProps<{
  title?: string
  likes: number
}>()

Prop 默认值

使用 withDefaults 编译器宏为类型声明的 props 提供默认值:

interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two']
})

Prop 校验

可以为 props 指定更详细的验证要求:

defineProps({
  // 基础类型检查
  propA: Number,
  // 多个可能的类型
  propB: [String, Number],
  // 必填的字符串
  propC: {
    type: String,
    required: true
  },
  // 带默认值的数字
  propD: {
    type: Number,
    default: 100
  },
  // 自定义验证函数
  propE: {
    validator(value) {
      return ['success', 'warning', 'danger'].includes(value)
    }
  }
})

注意事项

  1. defineProps 只能在 <script setup> 中使用
  2. 声明的 props 会自动暴露给模板,无需通过 setup() 返回
  3. 在 TypeScript 中,可以通过接口或类型别名来定义 props 类型
  4. props 是响应式的,但不能直接解构,否则会失去响应性
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐