Fork me on GitHub

Vue组件通信模式

Vue组件通信模式

前几天百度电面了我,问了一些vue框架的相关知识。可惜,学的太不全面了,有一些是问倒了我。组件间通信我重新学习了下,进行一个总结。(可能还不是很完善- -)

Vue组件通信模式

属性和事件

属性

属性允许你传递任意的数据类型到一个子组件中,并且允许你控制组件接收何种类型的数据。属性的更新也是响应式的,这使得无论任何时候,父组件的数据改变,子组件就会更新。
以下是父组件传值到子组件的例子:

  • HTML代码:
1
2
3
4
<div id="exp1">
<input v-model="parentmsg">{{parentmsg}}</input>
<child :childmsg="parentmsg"></child>
</div>
  • JS代码:
1
2
3
4
5
6
7
8
9
10
11
12
Vue.component('child', {
template:`<p>{{childmsg}}</p>`,
props: ['childmsg']
})
let vm1 = new Vue({
el: "#exp1",
data(){
return {
parentmsg: '1111'
}
}
})
事件

事件提供了一种子组件通知父组件做出改变的方式。
以下是子组件传值到父组件的例子:

  • HTML代码:
1
2
3
4
<div id="exp2">
<p v-for="msg in parentMsg">{{msg}}</p>
<child-button @message="handleParentMsg"></child-button>
</div>
  • JS代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Vue.component('child-button', {
template: `
<div>
<input v-model="childmsg" />
<button @click="handleChildMsg">Send</button>
</div>
`,
data() {
return {
childmsg: '1234'
}
},
methods: {
handleChildMsg: function () {
this.$emit('message', { message: this.childmsg });
}
}
})

let vm2 = new Vue({
el: "#exp2",
data() {
return {
parentMsg: []
}
},
methods: {
handleParentMsg: function (payLoad) {
this.parentMsg.push(payLoad.message);
}
}
})

事件总线

创建一个全局事件总线来在任意位置传递事件。可用于非父子组件间的通信。参照此文章
先创建一个空的Vue实例作为总线。总线可单独放置在一个js文件独立开来。
如event-bus.js:

1
2
import Vue from 'vue’;
export const EventBus = new Vue();

创建PleaseClickMe.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
<div class="pleeease-click-me" @click="emitGlobalClickEvent()"></div>
</template>

<script>
// 导入创建的event-bus.js
import { EventBus } from './event-bus.js';

export default {
data() {
return {
clickCount: 0
}
},

methods: {
emitGlobalClickEvent() {
this.clickCount++;
// 点击触发事件并传递载荷(the clickCount)
EventBus.$emit('i-got-clicked', this.clickCount);
}
}
}
</script>

再创建receive.vue:

1
2
3
4
5
6
import { EventBus } from './event-bus.js';

// 监听i-got-clicked事件和接收传递过来的载荷
EventBus.$on('i-got-clicked', clickCount => {
console.log(`Oh, that's nice. It's gotten ${clickCount} clicks!`)
});

Provide / Inject

provide/inject机制是Vue一个比较新的特性。它可以选择性的暴露祖先组件的数据或者方法到其所有的后代中。
provide 选项应该是一个对象返回一个对象的函数
inject 选项应该是一个字符串数组,或一个对象

这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。

  • 官方示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//父组件
var Provider = {
provide: {
foo: 'bar'
},
// ...
}

//子组件
var Child = {
inject: ['foo'],
created () {
console.log(this.foo) // => "bar"
}
// ...
}