vue3中实现组件通信方式总结

1、基础的父子通信—父传子

父组件通过属性绑定传值,子组件通过defineProps接收
父组件可以传递具体的值,也可以传递变量
子组件接受可以通过数组的方式,或对象的方式接收
示例demo:
父组件:

<template>
  <div class="box">
    <!-- 2、使用组件,并传值【message传的是字符串,num传递的是变量】 -->
    <Child message="父组件传给子组件的一段文本值" :num="num"></Child>
  </div>
</template>

<script setup lang="ts">
// 1、引入子组件
import Child from './Child.vue'

import {
   ref} from 'vue'
const num = ref(100)

</script>

<style scoped>
.box {
   
  display: flex;
  justify-content: center;
  align-items: center;
  width: 400px;
  height: 400px;
  background: rgb(248, 255, 233);
}
</style>

子组件Child

<template>
  <div class="son">
    <!-- 4、在子组件中使用 -->
    <h4>{
   {
    message }}</h4>
    <h4>父组件传递的变量:{
   {
    num }}</h4>
  </div>
</template>

<script setup lang="ts">

// 3、defineProps接收值
// 3.1通过数组的方式接收值
// defineProps(['num','message'])
// 3.2或通过对象的方式接收值
defineProps({
   
  message:String,
  num:Number
})


</script>

<style scoped>
.son{
   
  width: 300px;
  height: 300px;
  background: rgb(227, 210, 219);
}
</style>

效果图:
在这里插入图片描述

2、基础的父子通信—子传父

子组件通过自定义事件传值,父组件通过@自定义事件接收
子组件:

<template>
  <div class="son">
    <!-- 4、子组件中使用 -->
    <h4>{
   {
    message }}</h4>
    <h4>父组件传递的变量:{
   {
    num }}</h4>
    <button @click="handler">num+10</button>
  </div>
</template>

<script setup lang="ts">
// props的值是只读的,修改父组件传的值,通过自定义事件给父组件传值,通知父组件修改
// 3、defineProps接收值
// 3.1通过数组的方式接收值
// defineProps(['num','message'])
// 3.2通过变量的方式接收值
defineProps({
   
  message:String,
  num:Number
})

// a、子组件通过defineEmits传值
const emits = defineEmits(['addNum'])
const handler= ()=>{
   
  emits('addNum',10)
}


</script>

<style scoped>
.son{
   
  width: 300px;
  height: 300px;
  background: rgb(227, 210, 219);
}
</style>

父组件:

<template>
  <div class="box">
    <!-- 2、使用组件,并传值【message传的是字符串,num传递的是变量】 -->
    <Child message="父组件传给子组件的一段文本值" :num="num" @addNum="handler"></Child>
  </div>
</template>

<script setup lang="ts">
// 1、引入子组件
import Child from './Child.vue'

import {
   ref} from 'vue'
const num = ref(100)

// b、父组件接收值
const handler = (e:any)=>{
   
  num.value += e
}
</script>

<style scoped>
.box {
   
  display: flex;
  justify
  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值