父组件文件:parentcomponent.vue
子组件文件:childcomponent.vue
- 传普通值
- 传动态值
- 传对象
- 传数组
<!-- 父组件 -->
<template>
<h1>I am ParentComponent</h1>
<ChildComponent msg="nice"/>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
</script>
一、传普通值
<!-- 父组件 -->
<template>
<h1>I am ParentComponent</h1>
<ChildComponent msg="nice"/>
</template>
<script setup> import ChildComponent from './ChildComponent.vue'
</script>
<!-- 子组件 -->
<template>
<h2>I am ChildComponent</h2>
<p>I want {{ props.msg }} from my Parent.</p>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({ msg:String, })
</script>
二、传动态值
<!-- 父组件 -->
<template>
<h1>I am ParentComponent</h1>
<ChildComponent :msg="message"/>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
const message = "动态传值"
</script>
![](https://img2024.cnblogs.com/blog/1593465/202407/1593465-20240704145001935-825774874.png)
可能会有疑惑,defineProps是什么呢?
它其实就是一个API函数。defineProps
是 Vue 3 中的一个函数,用于定义组件的 props。与 Vue 2 中的 props
配置选项不同,使用 defineProps
函数定义的 props 是只读的响应式对象,它们的值由父组件传递而来,不能被子组件修改。这有助于提高组件的可维护性和可重用性,并减少不必要的副作用。 简单理解:就是用于拿父组件传过来的值,且子组件不能修改!
三、传对象
<!-- 父组件 -->
<template>
<h1>I am ParentComponent</h1>
<ChildComponent :arrMsg="A"/>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
const A = [
{id:1,name:'Kiangkiang'},
{id:2,name:'Xiaohong'},
{id:3,name:'Xiaoma'}
]
</script>
<!-- 子组件 -->
<template>
<h2>I am ChildComponent</h2>
<h3>数组</h3>
<ul v-for="item in props.arrMsg" :key="item.id">
<li>{{ item.id }}-{{ item.name }}</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
arrMsg:Array//接收父组件ParentComponent传过来的数组
})
</script>
四、传数组
<!-- 父组件 -->
<template>
<h1>I am ParentComponent</h1>
<ChildComponent :list="ListMsg"/>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
const ListMsg = {
name:'Xiaoma', age:'18', gender:'Boy',
}
</script>
<!-- 子组件 -->
<template>
<h2>I am ChildComponent</h2>
<h3>个人信息</h3>
<ul>
<li>{{ props.list.name }}</li>
<li>{{ props.list.age }}</li>
<li>{{ props.list.gender }}</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
list:Object,
})
</script>
![](https://img2024.cnblogs.com/blog/1593465/202407/1593465-20240704145752217-1475096487.png)