vue中的 $attrs 與 $listeners ,主要是作為一個中間層,承接組件外部與內部的屬性與方法。
示例:
// child.vue
1 <template lang="pug"> 2 .child-page 3 .text 展示code:{{code}} 4 el-button(v-bind="$attrs" v-on="$listeners") 5 slot 6 </template> 7 <script> 8 export default { 9 props: ["code"] //單獨領出來放在props里的屬性可以通過this[key]獲取,否則如果這個code不放在props,那this.code是獲取不到的,都會被傳入到$attrs里去 10 }; 11 </script>
// parent.vue
1 <template lang="pug"> 2 child(type="primary" size="small" @click="dian" code="btnCode") 點擊 3 </template> 4 <script> 5 import child from "./child" 6 export default { 7 components:{child}, 8 methods: { 9 dian() { 10 console.log("點擊了"); 11 } 12 } 13 }; 14 </script>
展示效果:
如果不使用$attrts 與 $listeners,那么會增加很多的代碼量,代碼不夠優美簡約,示例如下:
// child.vue
1 <template lang="pug"> 2 .child-page 3 .text 展示code:{{code}} 4 // 麻煩1 :要把props都列出來傳給按鈕; 麻煩2:還得把對應的事件emit出去 5 el-button(:disabled="disabled" :size="size" :type="type" @click="()=>{this.$emit('click')}") 6 slot 7 </template> 8 <script> 9 export default { 10 props: ["code", "disabled", "size", "type"] //麻煩3:要列出一些列按鈕需要的props,非常麻煩 11 }; 12 </script>
parent.vue沒有改動
總結:$attrs 與 $listeners ,主要是作為一個中間層,承接組件外部與內部的屬性與方法。將外部傳送的props都通過
v-bind="$attrs"傳給內部的組件;將外部執行的事件,通過v-on="$listeners"傳給內部的組件。
在使用 $attrs 需要注意一下,如果自身組件也需要使用這個屬性,如上述例子中的code,那么需要在props中把code這個屬性拎出來,不然都用$attrs傳到下面組件的話,自身this.code是獲取不到值的。