欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 组件通信-$refs、$parent

组件通信-$refs、$parent

2025/5/3 8:14:42 来源:https://blog.csdn.net/karlaofsky/article/details/147671481  浏览:    关键词:组件通信-$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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词