组件通信的四大类 父与子 子与父 子与子 跨层级
大概列举vue的通信方法有
1.props和$emit 2、provide和inject 3、$parent和$children 4、$attrs和$listeners
5、中央事件总线bus 6.vuex
1、props / $emit
最常用的一种父子间传递数据的方式。
父组件通过绑定属性来向子组件传递数据,子组件通过 props 属性来获取对应的数据;子组件通过 $emit 事件向父组件发送消息,将自己的数据传递给父组件。
// 父组件Father
<template>
<div>
<Son
:title="value"
:moreBtn="moreBtn"
@more="onMore"/>
</div>
</template>
<script>
import Son from './Son
export default{
name: 'Father',
components:{
Son
},
data(){
return {
value: '',
moreBtn: true
}
},
method:{
onMore(value){
console.log('value', value)
//接收到子组件的值
}
}
}
</script>
//子组件Son
<template>
<div>
<div class="title">{{value}}</div>
<div v-if="moreBtn" @click="handleMore">查看更多</div>
</div>
</template>
<script>
export default{
name: 'compB',
data(){
return {
}
},
props: {
title: {
type: String,
default: '标题'
},
moreBtn: {
type: Boolean,
default: false
}
}
method:{
handleMore(){
this.$emit('more', '传值给父组件 ')
}
}
}
</script>
2、provide / inject
父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量。不论子组件有多深,只要调用了 inject那么就可以注入provider中的数据。而不是局限于只能从当前父组件的prop属性来获取数据,只要在父组件 的生命周期内,子组件都可以调用。
// 父组件
<template>
<div>
<com-a></com-a>
</div>
</template>
<script>
import ComA from './a';
export default {
'name': 'home',
'components': {ComA},
provide() {
return {
'a': 'Hello',
'show': val => !val
};
}
};
</script>
// 子组件
<template>
<div>
<el-button @click="showFn(textShow)">点击我切换下面文字展示及隐藏</el-button>
<div v-if="textShow">我是一段随意被操控的文字{{a}}</div>
</div>
</template>
<script>
export default {
'name': 'ComA',
data() {
return {'textShow': true};
},
'inject': [
'a',
'show'
],
'methods': {
showFn(val) {
this.textShow = this.show(val);
}
}
};
</script>