当前位置:网站首页>$parent/$children and ref
$parent/$children and ref
2022-07-31 03:33:00 【The life of an elephant and an ant】
- 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
边栏推荐
- 浅识Flutter 基本组件之CheckBox组件
- PMP WeChat group daily exercises
- IDEA comment report red solution
- [Compilation principle] Design principle and implementation of recursive descent parsing
- WebSocket Session is null
- 【编译原理】词法分析程序设计原理与实现
- Atomic operation CAS
- Component pass value provide/inject
- Mysql 45 study notes (twenty-five) MYSQL guarantees high availability
- MP使用时的几个常见报错
猜你喜欢

IIR filter and FIR filter
![[C language] General method of expression evaluation](/img/59/cf43b7dd16c203b4f31c1591615955.jpg)
[C language] General method of expression evaluation

STM32问题合集

《DeepJIT: An End-To-End Deep Learning Framework for Just-In-Time Defect Prediction》论文笔记

LeetCode每日一练 —— OR36 链表的回文结构

Ambiguous method call.both
![[C language] Preprocessing operation](/img/69/0aef065ae4061edaf0d96b89846bf2.png)
[C language] Preprocessing operation

SIP Protocol Standard and Implementation Mechanism

LeetCode simple problem to find the subsequence of length K with the largest sum

Redis implements distributed locks
随机推荐
识Flutter 基本组件之showTimePicker 方法
【编译原理】递归下降语法分析设计原理与实现
SocialFi 何以成就 Web3 去中心化社交未来
LeetCode中等题之分数加减运算
Difference between unallocated blocks and unused blocks in database files
How to develop a high-quality test case?
Redis 使用LIST做最新评论缓存
《DeepJIT: An End-To-End Deep Learning Framework for Just-In-Time Defect Prediction》论文笔记
MultipartFile文件上传
[C language] Three-pointed chess (classic solution + list diagram)
MultipartFile file upload
The application and practice of mid-to-platform brand advertising platform
数据库文件中的未分配的块和未使用的块的区别
$parent/$children 与 ref
5. How does the SAP ABAP OData service support the $filter operation
[Compilation principle] Lexical analysis program design principle and implementation
[Godot][GDScript] 2D cave map randomly generated
$attrs/$listeners
CloudCompare&PCL 计算两个点云之间的重叠度
Daily practice of LeetCode - palindrome structure of OR36 linked list