多级组件嵌套需要传递数据时,通常使用的方法是通过vuex。但如果仅仅是传递数据,而不做中间处理,使用vuex,为此Vue2.4 版本提供了其他方法----$attrs/$listeners/$props
$attrs:父组件传到当前组件的参数$listeners:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件$props:当前组件接收的参数--当前组件接收到的 props 对象。Vue 实例代理了对其 props 对象属性的访问。
// App.vue
<child1-vue
msg="child1"
:foo="foo"
:boo="boo"
:doo="doo"
:coo="coo"
@test-listen.native='testListen'
@test-listen1='testListen1'
@get='getNum'/>
<script>
export default {
methods:{
//可以看到$listeners中不含 带有 .native 修饰符的函数
testListenNative() { window.console.log('主页接收') },
testListen() { window.console.log('主页接收,没有native'); },
getNum(num) { window.console.log('获取值'+num); },
}
}
</script>
// child1.vue
<template>
<div class="hello">
<div>父组件传递的 $attrs:{{$attrs}}</div>
<div> 当前页面接收的 $props:{{$props}}</div>
<!-- 打印$listeners : [test-listen,get] -->
<child2-vue v-bind="$attrs" v-on="$listeners" @other-get="otherGet"></child2-vue>
</div>
</template>
<script>
export default {
props: {
msg: String,
// foo: String // foo作为props属性绑定
},
components:{
Child2Vue
},
inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性
}
</script>
// child3.vue
<template>
<div class="hello">
<div>父组件传递的 $attrs:{{$attrs}}</div>
<div> 当前页面接收的 $props:{{$props}}</div>
</div>
</template>
<script>
export default {
props: {
// coo: String // foo作为props属性绑定
},
}
</script>
$attrs/$listeners/$props都是变量,可以层层传递。 注意:如果中途有一个参数被写在props属性中(如:props:{foo:String}),那么$attrs中会相应的除去该属性。将$attrs中的属性写到$props中