vue组件之间的通信

组件的分类

常规页面组件

由 vue-router 产生的每个页面,它本质上也是一个组件( .vue),主要承载当前页面的 HTML 结构,会包含数据获取、数据整理、数据可视化等常规业务。

功能性抽象组件

不包含业务,独立、具体功能的基础组件,比如日期选择器、弹窗警告等。这类组件作为项目的基础控件,会被大量使用,因此组件的 API 进行过高强度的抽象,可以通过不同配置实现不同的功能。

业务组件

它不像第二类独立组件只包含某个功能,而是在业务中被多个页面复用的,它与独立组件的区别是,业务组件只在当前项目中会用到,不具有通用性,而且会包含一些业务,比如数据请求;而独立组件不含业务,在任何项目中都可以使用,功能单一,比如一个具有数据校验功能的输入框。

父组件向子组件传值 prop

英式发音:[prɒp]

prop接收的数据 类型

refAge: {
type: Number,
default: 0
},
refName: {
type: String,
default: ''
},
hotDataLoading: {
type: Boolean,
default: false
},
hotData: {
type: Array,
default: () => {
return []
}
},
getParams: {
type: Function,
default: () => () => {}
},
meta: {
type: Object,
default: () => ({})
}

代码:

<div id="app">
  <child :content="message"></child>
</div>

// Js
let Child = Vue.extend({
  template: '<h2>{{ content }}</h2>',
  props: {
    content: {
      type: String,
      default: () => { return 'from child' }
    }
  }
})
new Vue({
  el: '#app',
  data: {
    message: 'from parent'
  },
  components: {
    Child
  }
})

浏览器输出:from parent

子组件向父组件传值 $emit

英式发音:[iˈmɪt]

<div id="app">
  <my-button @greet="sayHi"></my-button>
</div>
let MyButton = Vue.extend({
  template: '<button @click="triggerClick">click</button>',
  data () {
    return {
      greeting: 'vue.js!'
    }
  },
  methods: {
    triggerClick () {
      this.$emit('greet', this.greeting)
    }
  }
})
new Vue({
  el: '#app',
  components: {
    MyButton
  },
  methods: {
    sayHi (val) {
      alert('Hi, ' + val) // 'Hi, vue.js!'
    }
  }
})

EventBus

思路就是声明一个全局Vue实例变量 EventBus , 把所有的通信数据,事件监听都存储到这个变量上。这样就达到在组件间数据共享了,有点类似于 Vuex。但这种方式只适用于极小的项目,复杂项目还是推荐 Vuex。下面是实现 EventBus 的简单代码:

<div id="app">
  <child></child>
</div>
// 全局变量
let EventBus = new Vue()
// 子组件
let Child = Vue.extend({
  template: '<h2>child</h2>',
  created () {
    console.log(EventBus.message)
    // -> 'hello'
    EventBus.$emit('received', 'from child')
  }
})
new Vue({
  el: '#app',
  components: {
    Child
  },
  created () {
    // 变量保存
    EventBus.message = 'hello'
   // 事件监听
    EventBus.$on('received', function (val) {
      console.log('received: '+ val)
      // -> 'received: from child'
    })
  }
})

Vuex

有文章:https://www.jianshu.com/p/79f8d6ab54ca

任意组件的通信

找到任意组件实例——findComponents 系列方法

它适用于以下场景:

由一个组件,向上找到最近的指定组件;
由一个组件,向上找到所有的指定组件;
由一个组件,向下找到最近的指定组件;
由一个组件,向下找到所有指定的组件;
由一个组件,找到指定组件的兄弟组件。
5 个不同的场景,对应 5 个不同的函数,实现原理也大同小异。

1、向上找到最近的指定组件——findComponentUpward

// 由一个组件,向上找到最近的指定组件
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;
}
export{
 findComponentUpward 
};

比如下面的示例,有组件 A 和组件 B,A 是 B 的父组件,在 B 中获取和调用 A 中的数据和方法:

<!-- component-a.vue -->
<template> 
    <div>
        组件 A 
        <component-b></component-b>
    </div>
</template>
<script>  
import componentB from './component-b.vue';
export default{
    name:'componentA',
    components:{
          componentB 
    },
    data (){      
        return{
              name:'Aresn'  
        }   
   },
    methods:{
      sayHello (){
        console.log('Hello, Vue.js');      
       }    
}  
}
</script>
<!-- component-b.vue -->
<template>  
    <div>
        组件 B
    </div>
</template>
<script>
import { findComponentUpward } from '../utils/assist.js';  
export default {
    name:'componentB',
    mounted (){
        const comA = findComponentUpward(this,'componentA');
        if(comA){
            console.log(comA.name);
            // Aresn
            comA.sayHello();
           // Hello, Vue.js
}    
}  
}
</script>

2、向上找到所有的指定组件——findComponentsUpward

// 由一个组件,向上找到所有的指定组件
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

[];

}
}
export

{
findComponentsUpward
};
3、向下找到最近的指定组件——findComponentDownward

// 由一个组件,向下找到最近的指定组件
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
;
}
export

{
findComponentDownward
};
4、向下找到所有指定的组件——findComponentsDownward

// 由一个组件,向下找到所有指定的组件
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
);

},

[]);
}
export

{
findComponentsDownward
};
5、找到指定组件的兄弟组件——findBrothersComponents

// 由一个组件,找到指定组件的兄弟组件
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
;
}
export

{
findBrothersComponents
};
相比其它 4 个函数, findBrothersComponents 多了一个参数 exceptMe,是否把本身除外,默认是 true。寻找兄弟组件的方法,是先获取 context.parent.children,也就是父组件的全部子组件,这里面当前包含了本身,所有也会有第三个参数 exceptMe。Vue.js 在渲染组件时,都会给每个组件加一个内置的属性 _uid,这个 _uid 是不会重复的,借此我们可以从一系列兄弟组件中把自己排除掉。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容