1. 多层组件参数传递
vue组件之间通信
- 使用props和$emit的方式:多级组件中传参太麻烦
- vuex:较复杂
- 使用v-bind="$attrs",将父组件中非props的绑定的属性传入子组件中。
- provide和inject
接下来着重介绍③和④
1.1 v-bind=“attrs"和v−on="attrs" 和 v-on="attrs"和v−on="listeners”
举个例子
top组件:
<template>
<div>
<centers name="name"
age="18"
aaa="666"
bbb="777"
@isClick="isClick"
@asd="asd"></centers>
</div>
</template>
<script>
import centers from '~/components/center';
export default {
components: { centers },
methods: {
asd() {
console.log(999);
},
isClick() {
console.log(666);
}
}
};
</script>
top组件传入name,age,aaa,bbb参数
center组件:
<template>
<div>
<div class="mt-10">
<bottom v-bind="$attrs" v-on="$listeners" />
</div>
</div>
</template>
<script>
import bottom from '~/components/bottom';
export default {
components: { bottom },
props: {
name: {
type: String,
default: 'default'
},
age: {
type: String,
default: 'default'
}
}
};
</script>
enter组件只接收了name,age属性,而bottom组件想使用aaa属性怎么办呢?
center组件通过v-bind="$attrs"
将其他参数传递给bottom组件,于是bottom组件就能使用到aaa参数了
bottom组件:
<template>
<div>
<div>
{{ $attrs['aaa'] }} 在$attrs里面只会有props没有注册的属性
<br>
{{ aaa }}
</div>
</div>
</template>
<script>
export default {
props: {
aaa: {
type: String,
default: ''
}
},
mounted() {
console.log(this.$attrs); // top组件中的参数
console.log(this.$listeners); // top组件中定义的事件(方法)
this.$listeners.isClick();
this.$listeners.asd();
}
};
</script>
通过v-bind="$attrs"
将调用组件时的组件标签上绑定的非props的特性
(class和style除外)向下传递,v-on="$listeners"
将父组件标签上的自定义事件向下传递,其子组件可以直接通过emit(eventName)
的方式调用
1.2 provide和inject
成对出现:provide和inject是成对出现的
作用:用于父组件向子孙组件传递数据
父组件:
<template>
<div class="parent">
<child></child>
</div>
</template>
<script>
export default {
name: 'parent',
data () {
return {}
},
provide () { // 将参数注入
return {
config: {
skin: 'blue'
},
isDisplay: 5291
}
},
methods: {},
}
</script>
子组件
<template>
<div class="child">
<sub-child></sub-child>
</div>
</template>
孙组件:
export default {
name: 'sub-child',
data () {
return {}
},
inject: ['config', 'isDisplay'], // 获取祖先传入的参数
created () {
console.log('config', this.config)
console.log('isDisplay', this.isDisplay)
},
}
通过provide/inject可以轻松实现跨级访问父组件的数据