vue3中父子组件间的通信(js)

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>

运行结果

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值