inheritAttrs、$attrs和$listeners使用場景:
組件傳值,尤其是祖孫組件有跨度的傳值。
(1)inheritAttrs
屬性說明:https://cn.vuejs.org/v2/api/#inheritAttrs
說明比較晦澀。
組件傳值一般是通過props傳值的。inheritAttrs默認值為true,true的意思是將父組件中除了props外的屬性添加到子組件的根節點上(說明,即使設置為true,子組件仍然可以通過$attr獲取到props意外的屬性)。示例代碼:
grandpaDom.vue:
<template>
<div>
<father-dom :foo="foo" :coo="foo" v-on:upRocket="reciveRocket"
>
</father-dom>
</div>
</template>
<script> import fatherDom from "./fatherDom.vue"; export default { data() { return { foo:"Hello, world", coo:"Hello,rui" } }, components:{fatherDom}, methods:{ reciveRocket(){ window.console.log('火箭發射成功!') } } } </script>
fatherDom.vue:
<template>
<div>
<p>------------fatherDom-------------</p>
<p>attrs:{{$attrs}}</p>
<p>foo:{{foo}}</p>
<p>------------fatherDom-------------</p>
<child-dom v-bind="$attrs" v-on="$listeners"></child-dom>
</div>
</template>
<script> import childDom from "./childDom.vue"; export default { name:'father-dom', props:["foo"], components:{childDom}, } </script>
說明:grandpaDom.vue將foo和coo屬性都放在fatherDom.vue上,但是fatherDom.vue的props值接收了foo,因此grandpaDom的coo屬性顯示在了fatherDom的根節點上。即:
接着將inheritAttrs:false后(請將fatherDom.vue添加inheritAttrs:false),coo屬性就不會顯示在fatherDom根節點上了。但是怎么獲取到coo呢?
這時就通過$attrs獲取到到coo。
接着看孫組件childDom.vue:
<template>
<div>
<p>------------childDom-------------</p>
<p>coo:{{coo}}</p>
<button @click="startUpRocket">我要發射火箭</button>
<p>------------childDom-------------</p>
</div>
</template>
<script> export default { name: "childDom", props: ["coo"], methods: { startUpRocket() { this.$emit("upRocket"); window.console.log('我要發射火箭了。') } } }; </script>
孫組件childDom.vue就可以通過props接收到coo屬性了。
好,以上是總祖父--父親--兒子向下傳遞值。
那怎么兒子-父親--祖父傳遞數據呢呢?
父親組件使用$listeners傳遞。
最終祖父組件收到孫組件的事件了。
2020--06-18更新:
在封裝組件時非常有用:
<!-- 子組件 --> <template> <div class="" > <Button v-bind="$attrs" v-on="$listeners"> <slot /> </Button> <span>test</span> </div> </template> <script> export default { inheritAttrs: false, components: {}, data() { return {}; } }; </script> <style scoped> </style>
父組件:
<Test type='primary' @click="ss">2345</Test>