在Vue 3中,props是用于组件间传递数据的一种机制。你可以通过props传递多种数据类型。以下是一些示例:
- 传递一个字符串:
<!-- ParentComponent.vue -->
<template>
<ChildComponent title="Hello, World!" />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ title }}</div>
</template>
<script>
export default {
props: ['title']
}
</script>
- 传递一个数字:
<!-- ParentComponent.vue -->
<template>
<ChildComponent count="10" />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
props: ['count']
}
</script>
- 传递一个布尔值:
<!-- ParentComponent.vue -->
<template>
<ChildComponent isActive />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ isActive }}</div>
</template>
<script>
export default {
props: ['isActive']
}
</script>
- 传递一个数组:
<!-- ParentComponent.vue -->
<template>
<ChildComponent items="1, 2, 3" />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ items }}</div>
</template>
<script>
export default {
props: ['items']
}
</script>
- 传递一个对象:
<!-- ParentComponent.vue -->
<template>
<ChildComponent attributes="{ id: 1, name: 'Vue' }" />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ attributes }}</div>
</template>
<script>
export default {
props: ['attributes']
}
</script>
- 使用
v-bind
动态绑定props:
<!-- ParentComponent.vue -->
<template>
<ChildComponent :title="message" />
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue 3!'
}
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<div>{{ title }}</div>
</template>
<script>
export default {
props: ['title']
}
</script>
- 传递多个props:
<!-- ParentComponent.vue -->
<template>
<ChildComponent title="Hello, World!" count="10" isActive />
</template>
<!-- ChildComponent.vue -->
<template>
<div>{{ title }} - {{ count }} - {{ isActive }}</div>
</template>
<script>
export default {
props: ['title', 'count', 'isActive']
}
</script>
- 使用类型检查:
<!-- ChildComponent.vue -->
<template>
<div>{{ title }}</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
}
</script>
- 使用默认值:
<!-- ChildComponent.vue -->
<template>
<div>{{ count }}</div>
</template>
<script>
export default