一、父传子
父组件
<template>
<div class="hello">
我是父组件
<!-- 父组件通过:变量(这里是info)绑定值 也可以不用:常量例如info="123" -->
<Child :info="parentMsg"></Child>
</div>
</template>
<script setup>
import Child from './Child'
import {ref} from 'vue'
const parentMsg=ref('父组件传递值是a')
</script>
子组件
<template>
//通过props.传过来的值来使用
<div>我是子组件拿到了父组件的值是{{props.info}}</div>
</template>
<script setup>
import { toRefs, defineProps } from 'vue'
const props = defineProps({
//子组件接收父组件传递过来的值
info: String,
})
</script>
二、子传父
子组件
<template>
<button @click="click">点击子组件</button>
</template>
<script setup>
import { defineEmits } from 'vue'
// 使用defineEmits创建名称,接受一个数组声明emit可以传的值
const emit = defineEmits(['clickChild'])
const click=()=>{
let param={
content:'b'
}
//传递给父组件 引号中的值必须是emit中声明了的
emit('clickChild',param)
}
</script>
父组件
<template>
<div class="hello">
<!-- clickChild是子组件传值时声明的类型 -->
<Child @clickChild="clickEven"></Child>
</div>
</template>
<script setup>
import Child from './Child'
import {ref} from 'vue'
const clickEven=(val)=>{
console.log(val);
}
</script>
三、父组件使用子组件中的属性值
子组件
<template>
<div>
<p>性别:{{ sex}}</p>
</div>
</template>
<script setup>
import { reactive, ref,defineExpose } from "vue";
let sex=ref('男')
let info=reactive({
like:'王者荣耀',
age:18
})
defineExpose({sex, info}) //defineExpose({})包裹想给父组件使用的值
</script>
父组件
<template>
<div class="hello">
//要给子组件绑定一个ref
<Child ref="testcomRef"></Child>
<button @click="getSonHander">获取子组件中的数据</button>
</div>
</template>
<script setup>
import Child from './Child'
import {ref} from 'vue'
//声明给子组件绑定的ref
const testcomRef = ref()
const getSonHander=()=>{
console.log('获取子组件中的性别', testcomRef.value.sex );
console.log('获取子组件中的其他信息', testcomRef.value.info )
}
</script>