当前位置:网站首页>$parent/$children 与 ref
$parent/$children 与 ref
2022-07-31 03:19:00 【大象与小蚂蚁的生活】
- ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例
- $parent / $children:访问父 / 子实例
需要注意的是:这两种都是直接得到组件实例,使用后可以直接调用组件的方法或访问数据。我们先来看个用 ref 来访问组件的例子:
// component-a 子组件
export default {
data () {
return {
title: 'Vue.js'
}
},
methods: {
sayHello () {
window.alert('Hello');
}
}
}
// 父组件
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.title); // Vue.js
comA.sayHello(); // 弹窗
}
}
</script>
不过,这两种方法的弊端是,无法在跨级或兄弟间通信。
// parent.vue
<component-a></component-a>
<component-b></component-b>
<component-b></component-b>
我们想在 component-a 中,访问到引用它的页面中(这里就是 parent.vue)的两个 component-b 组件,那这种情况下,就得配置额外的插件或工具了,比如 Vuex 和 Bus 的解决方案。
总结
常见使用场景可以分为三类:
1.父子通信:
父向子传递数据是通过 props,
子向父是通过 events($emit);
通过父链 / 子链也可以通信($parent/$children);
ref 也可以访问组件实例;
provide/inject API;$attrs/$listeners
2.兄弟通信:
Bus;Vuex
3.跨级通信:
Bus;Vuex;provide/inject API、$attrs/$listeners
边栏推荐
猜你喜欢
endian mode
【C语言】进制转换一般方法
【编译原理】词法分析程序设计原理与实现
Web container and IIS --- Middleware penetration method 1
Ambiguous method call.both
The application and practice of mid-to-platform brand advertising platform
5. SAP ABAP OData 服务如何支持 $filter (过滤)操作
立足本土,链接全球 | 施耐德电气“工业SI同盟”携手伙伴共赴未来工业
浅识Flutter 基本组件之CheckboxListTile组件
【C语言】表达式求值的一般方法
随机推荐
刚出道“一战成名”,安全、舒适一个不落
How to develop a high-quality test case?
els block to the left to move the conditional judgment
品牌广告投放平台的中台化应用与实践
【CocosCreator 3.5】CocosCreator get network status
VS QT——ui不显示新添加成员(控件)||代码无提示
The distance value between two arrays of LeetCode simple questions
Mysql 45讲学习笔记(二十五)MYSQL保证高可用
Detailed explanation of TCP and UDP
Compile Hudi
Map.Entry理解和应用
C primer plus study notes - 8, structure
LeetCode简单题之两个数组间的距离值
解析小结—自用
【Cocos Creator 3.5】缓动系统停止所有动画
【C语言】三子棋(经典解法+一览图)
CorelDRAW2022 streamlined Asia Pacific new features in detail
浅识Flutter 基本组件之CheckBox组件
观察者模式
递归查询单表-单表树结构-(自用)