组件实例的引用方式

  • ref / $refs
  • $root
  • $parent
  • $children
  • 扩展查找任意组件实例的方法

在vue开发的项目中,通常会以一棵嵌套的组件树的形式来组织项目。

  • 都存在着一个根组件
  • 组件同时也都是 Vue 实例,组件间可以嵌套使用,形成了树状的级联形式,也就形成了父子组件、兄弟组件、祖先或后代组件这些关系。

在实际开发中,有时需要获取某个组件实例来引用其数据或方法。在前面讲解组件API的event时,通过ref / $refs调用组件实例来进行事件监听和触发。但$refs只能引用该组件下的子组件。

但实际上vue还提供其它几个API来获取组件实例$root / $parent / $children,我们也可以基于这些来扩展查找组件实例的便捷方法。

<div id="app">
<child1></child1>
</div>
const child1 = Vue.extend({template: `<div>子组件1<child1_1></child1_1></div>`})
const child1_1 = Vue.extend({
template: `<div>
<button @click="handleClick">子组件1_1,点击打印</button>
<child1_1_1></child1_1_1>
<child1_1_2 ref="child1_1_2"></child1_1_2/>
</div>`,
methods: {
handleClick() {
console.log('this:',this.$vnode.tag)
console.log('this.$root:',this.$root)
console.log('this.$parent:',this.$parent.$vnode.tag)
console.log('this.$children:',this.$children)
console.log('this.$children[0]:',this.$children[0].$vnode.tag)
console.log('this.$children[1]:',this.$children[1].$vnode.tag)
console.log('this.$refs.child1_1_2:',this.$refs.child1_1_2.$vnode.tag)
}
}
})
const child1_1_1 = Vue.extend({template: `<div>子组件1_1_1</div>`})
const child1_1_2 = Vue.extend({template: `<div>子组件1_1_2</div>`}) Vue.component('child1',child1)
Vue.component('child1_1',child1_1)
Vue.component('child1_1_1',child1_1_1)
Vue.component('child1_1_2',child1_1_2) const vm = new Vue({
el: "#app",
})
this: vue-component-2-child1_1
this.$root: Vue {_uid: 0, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
this.$parent: vue-component-1-child1
this.$children: [VueComponent, VueComponent]
this.$children[0]: vue-component-3-child1_1_1
this.$children[1]: vue-component-4-child1_1_2
this.$refs.child1_1_2: vue-component-4-child1_1_2

根据组件名称查找任意组件实例

点击查看参考链接:https://github.com/icarusion/vue-component-book

场景:

  • 由一个组件,向上找到最近的指定组件
  • 由一个组件,向上找到所有的指定组件
  • 由一个组件,向下找到最近的指定组件
  • 由一个组件,向下找到所有指定的组件
  • 由一个组件,找到指定组件的兄弟组件

实现:

结合$parent / $children,通过递归、遍历查找与指定组件的name选项匹配的组件实例。

// 由一个组件,向上找到最近的指定组件
function findComponentUpward (context, componentName) {
let parent = context.$parent;
let name = parent.$options.name; while (parent && (!name || [componentName].indexOf(name) < 0)) {
parent = parent.$parent;
if (parent) name = parent.$options.name;
}
return parent;
}
// 由一个组件,向上找到所有的指定组件
function findComponentsUpward (context, componentName) {
let parents = [];
const parent = context.$parent; if (parent) {
if (parent.$options.name === componentName) parents.push(parent);
return parents.concat(findComponentsUpward(parent, componentName));
} else {
return [];
}
}
// 由一个组件,向下找到最近的指定组件
function findComponentDownward (context, componentName) {
const childrens = context.$children;
let children = null; if (childrens.length) {
for (const child of childrens) {
const name = child.$options.name; if (name === componentName) {
children = child;
break;
} else {
children = findComponentDownward(child, componentName);
if (children) break;
}
}
}
return children;
}
// 由一个组件,向下找到所有指定的组件
function findComponentsDownward (context, componentName) {
return context.$children.reduce((components, child) => {
if (child.$options.name === componentName) components.push(child);
const foundChilds = findComponentsDownward(child, componentName);
return components.concat(foundChilds);
}, []);
}
// 由一个组件,找到指定组件的兄弟组件
// 每个vue组件实例都有一个唯一的_uid
function findBrothersComponents (context, componentName, exceptMe = true) {
let res = context.$parent.$children.filter(item => {
return item.$options.name === componentName;
});
let index = res.findIndex(item => item._uid === context._uid);
if (exceptMe) res.splice(index, 1);
return res;
}

vue-learning:30 - component - 组件实例的引用方式的更多相关文章

  1. VUE 动态加载组件的四种方式

    动态加载组件的四种方式: 1.使用import导入组件,可以获取到组件 var name = 'system'; var myComponent =() => import('../compon ...

  2. vue中js获取组件实例

    获取到的VM实例,外部js仍然能自由调用VM的一切属性和方法. <template> </template> <script> // 声明变量currVM let ...

  3. Vue中封装axios组件实例

    首先要创建一个网络模块network文件夹  里面要写封装好的几个组件 在config.js里面这样写 在index.js要这样写 core.js文件里面内容如下 然后要在main.js文件里面要设置 ...

  4. Vue加载组件、动态加载组件的几种方式

    https://cn.vuejs.org/v2/guide/components.html https://cn.vuejs.org/v2/guide/components-dynamic-async ...

  5. vue动态加载组件

    vue动态加载组件,可以使用以下方式 <component :is="propertyname" v-for="tab in tabs"></ ...

  6. 在被vue组件引用的 js 文件里获取组件实例this

    思路: 通过调用函数 把 组件实例this  传递 到 被应用的 js文件里 实例: 文件结构 在SendThis.vue 文件中引用 了modalConfig.js import modalConf ...

  7. 二、Vue组件(component):组件的相互引用、通过props实现父子组件互传值

    一.组件各部分说明及互相引用 1.一个vue组件由三个部分组成 Template 只能存在一个根元素 2.Script 3.Style scoped:样式只在当前组件内生效 1.1 组件的基本引用代码 ...

  8. 第七十七篇:ref引用(在vue中引用组件实例)

    好家伙, 为方便理解, 我们先来写一个经典自增一按钮, 再加上一个count清零按钮, Left.vue组件中: <template> <div > <h1>我是L ...

  9. vue构造函数(根实例化时和组件实例对象选项)参数:选项详解

    实例选项(即传给构造函数的options):数据,DOM,生命周期钩子函数,资源,组合,其他 数据 data 属性能够响应数据变化,当这些数据改变时,视图会进行重渲染. 访问方式: 1.通过 vm.$ ...

随机推荐

  1. nginx+tomcat集群+redis(memcache)session共享!

    常用保持session的方式: 1.一些代理(比如nginxIP_hash) 1.使用数据库来存储Session 2.使用Cookie来存储Session                       ...

  2. 洛谷 P3951 小凯的疑惑 找规律

    目录 题面 题目链接 题目描述 输入输出格式 输入格式: 输出格式: 输入输出样例 输入样例: 输出样例: 说明 思路 证明 AC代码 include<bits/stdc++.h> 题面 ...

  3. Python学习之路15☞socket编程

    一 客户端/服务器架构 即C/S架构,包括 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二 os ...

  4. COGS-2638 区间与,异或,询问max

    本篇题解参考了这个博客 题目链接 我们利用线段树来维护区间第最大值,考虑如何修改 每一次进行与操作时只有z的二进制为0的位会产生影响 每一次进行或操作时只有z的二进制为1的位会产生影响 所以只要该区间 ...

  5. Visual Studio中,无法嵌入互操作类型“……”,请改用适用的接口的解决方法

    解决方案:选中项目中引入的dll,鼠标右键,选择属性,把“嵌入互操作类型”设置为False,问题轻松解决. 问题分析: 1.”嵌入互操作类型”中的嵌入就是引进.导入的意思,类似于c#中using,c中 ...

  6. SGU 101 Domino【欧拉路径】

    题目链接: http://acm.sgu.ru/problem.php?contest=0&problem=101 题意: N个多米诺骨牌,每个骨牌左右两侧分别有一个0~6的整数(骨牌可以旋转 ...

  7. 复杂SQL示例 (排行榜需求)

    公司项目要求做出排行榜,根据六组数据依次排行,关联多表,SQL记录下来方便日后查看 " ?><!DOCTYPE mapper PUBLIC "-//mybatis.or ...

  8. 阿里云MaxCompute 2019-4月刊

    摘要: 4月新功能发布,精彩技术好文推荐,5月线上线下活动抢先知道,尽在4月刊. 您好,MaxCompute 2019.4月刊为您带来产品最新动态和丰富的产品技术内容,欢迎阅读. 导读 [功能发布]4 ...

  9. git 练习

    删除文件 git rm test.txt git  commit -m 'remove test.txt' 回复到最新版本 git checkout -- test.txt git checkout ...

  10. Python基础10 回顾

    从最初的"Hello World",走到面向对象,该回过头来看看,教程中是否遗漏了什么. 我们之前提到一句话,"Everything is Object".那么 ...