目录
一、父传子
①父组件准备参数
②父子连接点【父组件的子标签】
③子组件props接收数据
注意:在setup语法糖中,defineProps无需引入即可使用
1、父组件FatherView.vue
<script setup lang="ts">
import Son from '@/views/SonView.vue'
</script>
<template>
<div>
<Son title="基本信息"></Son>
</div>
</template>
2、子组件SonView.vue
<script setup lang="ts">
const props = defineProps({
title: {
type: String
}
});
</script>
<template>
<div>
<div>{{ props.title }}</div>
</div>
</template>
二、子传父
①子组件准备事件
注意:在setup语法糖中,defineEmits无需引入即可使用
②父子连接点【父组件的子标签】
格式:@事件='父组件自定义事件名'
③父组件使用函数,函数默认返回一个参数val,即子组件参数
1、子组件SonView.vue
<script setup lang="ts">
const emits = defineEmits(['click'])
const toFather = () => {
emits('click','我是子组件')
}
</script>
<template>
<div>
<div @click="toFather">子组件</div>
</div>
</template>
2、父组件FatherView.vue
<script setup lang="ts">
import Son from '@/views/SonView.vue'
const getSon = (val:any) => {
console.log(val);
}
</script>
<template>
<div>
<Son @click="getSon"></Son>
</div>
</template>
三、兄弟传参
1、兄弟组件2:BrotherView.vue
<script setup lang="ts">
const emits = defineEmits(['fromBrother'])
const toSon = () => {
emits('fromBrother','我有兄弟给的title啦')
}
</script>
<template>
<div>
<div @click="toSon">给兄弟一个title</div>
</div>
</template>
2、父组件【中间件】FatherView.vue
<script setup lang="ts">
import Son from '@/views/SonView.vue'
import Brother from '@/views/BrotherView.vue'
import { ref } from 'vue';
const title = ref('')
const getBrother = (val:any) => {
title.value = val
}
</script>
<template>
<div>
<Brother @fromBrother="getBrother"></Brother>
<Son :title="title"></Son>
</div>
</template>
3、兄弟组件1:SonView.vue
<script setup lang="ts">
const props = defineProps({
title:{
type:String,
default:''
}
})
</script>
<template>
<div>
<div>{{ props.title }}</div>
</div>
</template>
四、爷传孙
①爷组件准备参数,provide(),定义好参数名
②父组件,连接爷孙组件
③孙组件inject接收参数
1、爷组件GrandFatherView.vue
<script setup lang="ts">
import Father from '@/views/FatherView.vue'
import { provide,ref } from 'vue';
provide('id',ref(666))
</script>
<template>
<div>
<Father></Father>
</div>
</template>
2、父组件FatherView.vue
<script setup lang="ts">
import Son from '@/views/SonView.vue'
</script>
<template>
<div>
<Son></Son>
</div>
</template>
3、孙组件SonView.vue
<script setup lang="ts">
import { inject } from 'vue';
const userId = inject('id')
</script>
<template>
<div>
<div>{{ userId }}</div>
</div>
</template>
五、孙传爷
①爷组件provide,写好接收孙组件参数的方法
②父组件,连接爷孙组件
③孙组件inject,对应爷组件方法
1、爷组件
<script setup lang="ts">
import Father from '@/views/FatherView.vue'
import { provide } from 'vue';
const sendMoney:any = (val:any) => {
console.log(val);
}
provide('sendMoney',sendMoney)
</script>
<template>
<div>
<Father></Father>
</div>
</template>
2、父组件【同上第四点,不变】
3、孙组件SonView.vue
<script setup lang="ts">
import { inject } from 'vue';
const sendMoney = inject('sendMoney')
const toGrand = () => {
sendMoney(3000)
}
</script>
<template>
<div>
<div @click="toGrand">给爷爷点钱</div>
</div>
</template>