当前位置:网站首页>$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
边栏推荐
猜你喜欢
![[Swift] Customize the shortcut that pops up by clicking the APP icon](/img/d4/84b237995fc3d3700916eb57f6670d.png)
[Swift] Customize the shortcut that pops up by clicking the APP icon

大小端模式

LeetCode每日一练 —— 138. 复制带随机指针的链表

MP使用时的几个常见报错

Addition and Subtraction of Scores in LeetCode Medium Questions

端口排查步骤-7680端口分析-Dosvc服务

Mysql 45 study notes (twenty-four) MYSQL master-slave consistency

TCP详解(一)

7年经验,功能测试工程师该如何一步步提升自己的能力呢?

Redis implements distributed locks
随机推荐
els block to the right
MP使用时的几个常见报错
Web container and IIS --- Middleware penetration method 1
LeetCode简单题之找到和最大的长度为 K 的子序列
Mysql 45 study notes (23) How does MYSQL ensure that data is not lost
Select the smoke test case, and make the first pass for the product package entering QA
Point Cloud DBSCAN Clustering (MATLAB, not built-in function)
[C language] General method for finding the sum of the greatest common factor and the least common multiple of two integers m and n, the classical solution
BP神经网络
els 方块向右移
Ambiguous method call.both
安全20220715
Component pass value provide/inject
postgresql 15源码浅析(5)—— pg_control
STM32问题合集
Redis uses LIST to cache the latest comments
[Godot][GDScript] 2D cave map randomly generated
LeetCode简单题之两个数组间的距离值
False positives and false negatives in testing are equally worthy of repeated corrections
BUG definition of SonarQube