首先我们要明确props和emit是在父子组件(嵌套组件)中使用的 。
想要在父组件中渲染出子组件里的内容,需要在父组件中导入子组件,并在模板中渲染子组件。
那父子组件中如何通信呢?就需要使用到props和emit。
props
当子组件要接受父组件传递的数据信息时,也可以说是父组件传递数据给子组件时(子组件要显示父组件中的内容),需要使用props传递。
在子组件中,需要声明它所接受的props
<script setup>
const props = defineProps({
msg:string
})
</script>
<template>
{
{msg}}
</template>
在父组件中,导入子组件
<script setup>
import {ref} from 'vue'
import children from './children.vue'
导入之后,定义需要传输的数据
const hello=ref( 'hello,my friend')
</script>
<template>
在模板中的子组件内部动态绑定传输的数据
<