v-bind="$attrs" v-on="$listeners"
Vue 2.4 版本提供了這種方法,將父組件中不被認為 props特性綁定的屬性傳入子組件中,通常配合 interitAttrs 選項一起使用。之所以要提到這兩個屬性,是因為兩者的出現使得組件之間跨組件的通信在不依賴 vuex 和事件總線的情況下變得簡潔,業務清晰。

比如組件A=>B組件=>C組件等,這種多層級組件,A組件向C組件傳遞數據或者C組件的事件要觸發A組件中的事件的話,就可以在B組件中寫成
<template>
<div>
<span>{{child1}}<span>
<!-- C組件中能直接觸發test的原因在於 B組件調用C組件時 使用 v-on 綁定了$listeners 屬性 --> <!-- 通過v-bind 綁定$attrs屬性,C組件可以直接獲取到A組件中傳遞下來的props(除了B組件中props聲明的) --> <c v-bind="$attrs" v-on="$listeners"></c> </div> </template> <script> import c from './c.vue'; export default { props: ['child1'], data () { return {}; }, inheritAttrs: false, components: { c }, mounted () { this.$emit('test1'); } }; </script>
C組件
<template>
<div>
<span>{{child2}}<span>
</div>
</template>
<script>
export default { props: [child2'], data () { return {}; }, inheritAttrs: false, mounted () { this.$emit('test2'); } }; </script>
A組件:
<template>
<div id="app"> <b :child1="child1" :child2="child2" @test1="test1" @test2="test2"></b> </div> </template> <script> import b from './b.vue'; export default { data () { return { child1:'hello child1', child2:'hello child2' }; }, components: { b }, methods: { test1 () { console.log('test1'); }, test2 () { console.log('test2'); } } }; </script>