1、父传子
1.1、父亲代码
<!--父亲-->
<template>
<!-- 1、父亲在组价上写要传的值-->
<child :info="parentInfo"/>
</template>
<script lang="ts" setup>
import Child from "./child.vue";
const parentInfo = '我是父亲传给孩子的值'
</script>
1.2、孩子代码
<!-- 孩子-->
<template>
<div>我是孩子:{{ info }}</div>
</template>
<script lang="ts" setup>
// 1、在孩子上引入defineProps
import { defineProps } from 'vue'
// 2、使用efineProps接收值
defineProps({
info: {}
})
// 附: 也可以这样接收, 这样取值的时候就是 props.info
const props = defineProps({
info: {}
})
</script>
2、子传父
2.1、父亲代码
<!--父亲-->
<template>
<!-- 4、在父组价上写方法接收-->
<child @sendFromChild="parentGetInfo"/>
</template>
<script lang="ts" setup>
import Child from "./child.vue";
// 5、自定义方法接收
const parentGetInfo = (e) => {
console.log('e是父亲接收到子组件传过来的参数', e)
}
</script>
2.2、孩子代码
<!-- 孩子-->
<template>
<div @click="sendToParent">我是孩子:点我传给父亲</div>
</template>
<script lang="ts" setup>
// 前言,子传父如果只通过组件传参,那么只能子组件触发方法,父组件接收方法并调用方法才能传参
// 1、引入defineEmits
import { defineEmits } from 'vue'
// 2、定义emit, 数组内可以写多个 ['sendFromChild', 'xxxxxx', 'xxxx']
const emit = defineEmits(['sendFromChild'])
const sendToParent = () => {
// 3、调用方法(去父组件接收)
emit('sendFromChild', '我是孩子发给父亲的信息')
}
</script>
三、子传父
3.1、父亲代码
<!--父亲-->
<template>
<button @click="parentFunction">父亲的按钮</button>
<!-- 1、在父组件上写ref -->
<child ref="child"/>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import Child from "./child.vue";
// 2、定义一个变量,变量名一定和上面子组件ref内的一致
const child = ref(null)
// 5、最后父亲就可以调用了
const parentFunction =() => {
child.value.childFunction()
console.log(child.value.childInfo, '孩子中的变量')
}
</script>
3.2、孩子代码
<!-- 孩子-->
<template>
<div>我是孩子</div>
</template>
<script lang="ts" setup>
import { defineExpose, ref } from 'vue'
// 3、孩子上的函数
const childFunction = () => {
console.log('我是孩子,被父亲调用触发了')
}
// 3、孩子上的变量
const childInfo = ref("我是孩子里的信息")
// 4、一定要把让父亲调用的函数,或者读取的变量 用defineExpose给暴露出去
defineExpose({
childFunction,
childInfo
})
</script>