当前位置: 首页 > news >正文

组件通信-$refs、$parent

  1. 概述:

    • $refs用于 :父→子。

    • $parent用于:子→父。

  2. 原理如下:
属性说明
$refs值为对象,包含所有被ref属性标识的DOM元素或组件实例。
$parent值为对象,当前组件的父组件实例对象。

child1组件

<template><div class="child1"><h3>子组件1</h3><h4>玩具:{{ toy }}</h4><h4>书本:{{ book }}本</h4><button @click="minusHouse($parent)">干掉父亲的一套房产</button></div>
</template><script setup lang="ts" name="Child1">
import { ref } from 'vue'
const toy = ref('奥特曼')
const book = ref(3)
const minusHouse = (parent) => {parent.house--
}
// 把数据交给外部
defineExpose({ toy, book })
</script><style scoped>
.child1 {background-color: rgb(173, 148, 232);height: 100px;margin: 10px 0;
}
</style>

child2组件:

<template><div class="child2"><h3>子组件2</h3><h4>手机:{{ phone }}</h4><h4>书本:{{ book }}本</h4></div>
</template><script setup lang="ts" name="Child2">
import { ref } from 'vue'
const phone = ref('oppo')
const book = ref(6)
// 把数据交给外部
defineExpose({ phone, book })
</script>
<style scoped>
.child2 {background-color: aquamarine;height: 80px;
}
</style>

father组件:

<template><div class="father"><h3>父组件</h3><h4>房产:{{ house }}</h4><button @click="changeToy()">修改child1的玩具</button><button @click="changePhone()">修改child2的手机</button><button @click="getAllChild($refs)">让所有孩子的书变多</button><Child1 ref="c1" /><Child2 ref="c2" /></div>
</template><script setup lang="ts" name="Father">
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
import { ref } from 'vue'
const c1 = ref()
const c2 = ref()
const house = ref(6)
// 把数据交给外部
defineExpose({house})
const changeToy = () => {c1.value.toy = '小猪佩奇'
}
const changePhone = () => {c2.value.phone = '华为'
}
const getAllChild = (refs: any) => {console.log(refs)for (let key in refs) {refs[key].book += 3}
}
</script>
<style scoped>
.father {background-color: pink;width: 200px;height: 400px;padding: 20px;
}button {margin: 5px 0;
}
</style>

相关文章:

  • Linux-06-磁盘分区类命令
  • 高等数学-第七版-下册 选做记录 习题10-1
  • 邹晓辉教授十余年前关于围棋程序与融智学的思考,体现了对复杂系统本质的深刻洞察,其观点在人工智能发展历程中具有前瞻性意义。我们可以从以下三个维度进行深入解析:
  • 前端面试每日三题 - Day 22
  • 英伟达黄仁勋推荐的深度学习教程
  • aab转apk
  • 【Linux系统】进程间信号(捕捉信号)
  • 6.11.各顶点间的最短路径问题-Floyd算法
  • Redis基本使用
  • Git 基本操作(二)
  • AimRT从入门到精通 - 01实现一个helloworld
  • FHQ Treap
  • AI作画提示词:Prompts工程技巧与最佳实践
  • MYSQL-设计表
  • 消息队列的作用
  • [Verilog]跨时钟域数据传输解决方案
  • 2025五一数学建模竞赛A题完整分析论文(共45页)(含模型、可运行代码、数据)
  • spring中的@PostConstruct注解详解
  • 支持向量机(SVM)详解
  • 报文三次握手对么٩(๑^o^๑)۶
  • 党旗下的青春|赵天益:少年确定志向,把最好的时光奉献给戏剧事业
  • 见证历史与未来共舞:上海西岸“蝶变共生”对话讲坛圆满举行
  • 2025年第一批“闯中人”已经准备好了
  • 五大国货美妆去年业绩分化:珀莱雅百亿营收领跑,上海家化转亏
  • 宁波市纪委监委通报4起违反中央八项规定精神典型问题
  • 智能终端出海服务创新联合体成立