Vue 新增的$attrs与$listeners的详解
生活随笔
收集整理的這篇文章主要介紹了
Vue 新增的$attrs与$listeners的详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
$attrs
包含了父作用域中不作為 prop 被識別 (且獲取) 的特性綁定 (class?和?style?除外)。當一個組件沒有聲明任何 prop 時,這里會包含所有父作用域的綁定 (class和?style?除外),并且可以通過?v-bind="$attrs"?傳入內部組件——在創建高級別的組件時非常有用。
$listener
包含了父作用域中的 (不含?.native?修飾器的)?v-on?事件監聽器。它可以通過?v-on="$listeners"?傳入內部組件——在創建更高層次的組件時非常有用。
?
以上內容參考官網:https://cn.vuejs.org/v2/api/#vm-attrs
直接看使用代碼:
1 在父組件當中,最外層組件2 3 <template>4 <div>5 <Child1 :child1Info="child1" :child2Info="child2" v-on:test1="onTest1" v-on:test2="onTest2">6 </Child1>7 </div>8 </template>9 <script> 10 import Child1 from './child1'; 11 export default { 12 data() { 13 return { 14 child1:"hahha", 15 child2:"asdsdasd" 16 }; 17 }, 18 components: { Child1 }, 19 methods: { 20 onTest1(msg) { 21 console.log('test1 running...',msg); 22 }, 23 onTest2(msg) { 24 console.log('test2 running',msg); 25 } 26 } 27 }; 28 </script> 1 //在子組件中2 3 <template>4 <div class="child-1">5 <p>在子組件當中:</p>6 <p>props-child1Info: {{child1Info}}</p>7 <p>$attrs: {{$attrs}}</p>8 <hr>9 <!-- Child2組件中能直接觸發test的原因在于 B組件調用C組件時 使用 v-on 綁定了$listeners 屬性 --> 10 <!-- 通過v-bind 綁定$attrs屬性,Child2組件可以直接獲取到A組件中傳遞下來的props(除了child1組件中props聲明的) --> 11 <Child2 v-bind="$attrs" v-on="$listeners"></Child2> 12 </div> 13 </template> 14 <script> 15 import Child2 from './child2'; 16 export default { 17 props: ['child1Info'], 18 data() { 19 return {}; 20 }, 21 components: { Child2 }, 22 mounted() { 23 this.$emit('test1','嘻嘻'); 24 } 25 }; 26 </script> 1 //在孫子組件當中:2 3 4 <template>5 <div class="child-2">6 <p>在最里層組件當中child2:</p>7 <p>props-child2Info: {{child2Info}}</p>8 <p> $attrs 的值: {{$attrs}}</p>9 <hr> 10 </div> 11 </template> 12 <script> 13 export default { 14 props: ['child2Info'], 15 data() { 16 return {}; 17 }, 18 mounted() { 19 this.$emit('test2','哈哈'); 20 } 21 }; 22 </script>轉載于:https://www.cnblogs.com/baoshuyan66/p/11265854.html
總結
以上是生活随笔為你收集整理的Vue 新增的$attrs与$listeners的详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑开机自动进入biso怎么调 电脑开机
- 下一篇: 一台玉米打碎机一小时能打碎多少吨玉米杆