vue3中父子组件间的通信
defineProps函数
与props用法相似,使用时可以不用导入
父组件向子组件传递信息
父组件页面father.vue
<!-- father.vue -->
<script setup>
import { ref } from 'vue';
import son from './son.vue';
let text = ref('大头')
</script>
<template>
<div class='fatherContainer'>
<p>小头爸爸,</p>
<son :text="text"></son>
</div>
</template>
<style lang='less' scoped>
.fatherContainer {
position: absolute;
width: 150px;
height: 100px;
left: 10px;
top: 60px;
}
</style>
子组件页面
<!-- son.vue -->
<script setup>
defineProps({
text: {
type: String,
defaule: ''
}
})
</script>
<template>
<div class='sonContainer'>
小明才是{{ text }}儿子
</div>
</template>
<style lang='less' scoped></style>
主界面 app.vue
<!-- App.vue -->
<script setup>
import Father from './father.vue';
</script>
<template>
<Father />
</template>
<style scoped></style>
运行结果
defineEmit函数
获取emit函数,与defineProps函数一样不需要引入。
子组件向父组件传递信息
父组件father1.vue
<!-- father1.vue -->
<script setup>
import { ref } from 'vue';
import son1 from './son1.vue';
let num = ref(0)
const eat = (value) => {
num.value += value
}
</script>
<template>
<div class='fathercontainer'>
<p>围裙妈妈</p>
<p>小头儿子说要加{{ num }}块肉</p>
<son1 @add="eat"></son1>
</div>
</template>
<style lang='less' scoped>
.fathercontainer {
position: absolute;
text-align: left;
top: 0px;
left: 20px;
}
</style>
子组件son1.vue
在 emits() 的第一个参数为监听的自定义事件字面量,第二个参数为事件传递的参数。
如果该事件有多个参数要传递,可使用对象的形式进行传递。
<!-- son1.vue -->
<script setup>
const emit = defineEmits(['add']) // 自定义事件
const meat = () => { // 触发自定义事件
emit('add', 1)
}
</script>
<template>
<div class='soncontainer'>
<button @click="meat">🥩肉+1</button>
</div>
</template>
<style lang='less' scoped></style>
主界面 app.vue
<script setup>
import Father1 from './father1.vue';
</script>
<template>
<Father1 />
</template>
<style scoped></style>
运行结果