父传子
//父
<template>
<div class="hello">
我是父组件
<!-- 父组件通过:变量(这里是info)绑定值 -->
<Child :info="parentMsg"></Child>
</div>
</template>
<script setup>
import Child from './Child'
import {ref} from 'vue'
const parentMsg=ref('父组件传递值是a')
</script>
<style scoped>
</style>
//子
<template>
<!-- info是父组件传递过了的值 -->
<div>我是子组件拿到了父组件的值是{{info}}</div>
</template>
<script setup>
import { toRefs, defineProps } from 'vue'
const props = defineProps({
//子组件接收父组件传递过来的值
info: String,
})
//使用父组件传递过来的值
const {info} =toRefs(props)
</script>
<style>
</style>
子传父
<template>
<button @click="clickChild">点击子组件</button>
</template>
<script setup>
import { defineEmits } from 'vue'
// 使用defineEmits创建名称,接受一个数组
const emit = defineEmits(['clickChild'])
const clickChild=()=>{
let param={
content:'b'
}
//传递给父组件
emit('clickChild',param)
}
</script>
<style>
</style>
<template>
<div class="hello">
我是父组件
<!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->
<Child @clickChild="clickEven"></Child>
<p>子组件传递的值是 {{result}}</p>
</div>
</template>
<script setup>
import Child from './Child'
import {ref} from 'vue'
const result=ref('')
const clickEven=(val)=>{
console.log(val);
result.value=val.content
}
</script>
<style scoped>
</style>