Vue-- $attrs与$listeners的详解
生活随笔
收集整理的這篇文章主要介紹了
Vue-- $attrs与$listeners的详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vm.$attrs
- 2.4.0新增
- 類型 { [key: string]: string }
- 只讀
- 詳細
包含了父作用域中不作為 prop 被識別 (且獲取) 的特性綁定 (class 和 style 除外)。當一個組件沒有聲明任何prop 時,這里會包含所有父作用域的綁定 (class 和 style 除外),并且可以通過 v-bind="$attrs" 傳入內部組件——在創建高級別的組件時非常有用。
簡單點講就是包含了所以父組件在子組件上設置的屬性(除了prop傳遞的屬性、class 和 style )。
?
<div id="app"><base-inputlabel="姓名"class="name-input"placeholder="請輸入姓名"test-attrs="$attrs"></base-input></div>Vue.component("base-input", {inheritAttrs: true, //此處設置禁用繼承特性props: ["label"],template: `<label>{{label}}-{{$attrs.placeholder}}-<input v-bind="$attrs"/></label>`,mounted: function() {console.log(this.$attrs);}});const app = new Vue({el: "#app"});?
在生命周期方法mounted中打印$attrs,顯示除了calss和props定義的屬性之外的其他屬性。
通過 v-bind="$attrs" 傳入子組件內部的input標簽
?
vm.$listeners
- 2.4.0新增
- 類型 { [key: string]: Function | Array<Function> }
- 只讀
- 詳細
包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監聽器。它可以通過 v-on="$listeners" 傳入內部組件——在創建更高層次的組件時非常有用。
簡單點講它是一個對象,里面包含了作用在這個組件上所有的監聽器(監聽事件),可以通過 v-on="$listeners" 將事件監聽指向這個組件內的子元素(包括內部的子組件)。
為了查看方便,我們設置inheritAttrs: true,后面補充一下inheritAttrs。
?
<div id="app"><child1:p-child1="child1":p-child2="child2":p-child-attrs="1231"v-on:test1="onTest1"v-on:test2="onTest2"></child1></div><script>Vue.component("Child1", {inheritAttrs: true,props: ["pChild1"],template: `<div class="child-1"><p>in child1:</p><p>props: {{pChild1}}</p><p>$attrs: {{this.$attrs}}</p><hr><child2 v-bind="$attrs" v-on="$listeners"></child2></div>`,mounted: function() {this.$emit("test1");}});Vue.component("Child2", {inheritAttrs: true,props: ["pChild2"],template: `<div class="child-2"><p>in child->child2:</p><p>props: {{pChild2}}</p><p>$attrs: {{this.$attrs}}</p><button @click="$emit('test2','按鈕點擊')">觸發事件</button><hr> </div>`,mounted: function() {this.$emit("test2");}});const app = new Vue({el: "#app",data: {child1: "pChild1的值",child2: "pChild2的值"},methods: {onTest1() {console.log("test1 running...");},onTest2(value) {console.log("test2 running..." + value);}}});</script>上例中,父組件在child1組件中設置兩個監聽事件test1和test2,分別在child1組件和child1組件內部的child2組件中執行。還設置了三個屬性p-child1、p-child2、p-child-attrs。其中p-child1、p-child2被對應的組件的prop識別。所以:
p-child1組件中$attrs為{ "p-child2": "pChild2的值", "p-child-attrs": 1231 };
p-child2組件中$attrs為{ "p-child-attrs": 1231 }。
效果如下圖:
?
我們再點擊child2組件中的按鈕,觸發事件,控制臺可以打印出:
?
補充
inheritAttrs
- 2.4.0新增
- 類型 boolean
- 默認值:true
- 詳細
默認情況下父作用域的不被認作 props 的特性綁定 (attribute bindings) 將會“回退”且作為普通的 HTML 特性應用在子組件的根元素上。當撰寫包裹一個目標元素或另一個組件的組件時,這可能不會總是符合預期行為。通過設置 inheritAttrs 到 false,這些默認行為將會被去掉。而通過 (同樣是 2.4 新增的) 實例屬性 $attrs 可以讓這些特性生效,且可以通過 v-bind 顯性的綁定到非根元素上。
注意:這個選項不影響 class 和 style 綁定。
上例中同樣的代碼,設置了inheritAttrs: true,元素結構顯示如下圖:
沒有被 props綁定的屬性placeholder和test-attrs顯示到了子組件根節點上了。
下面我們把上例中設置inheritAttrs: false,元素結構顯示如下圖:
沒有被 props綁定的屬性就沒有作為普通的 HTML 特性應用在子組件的根元素上。
?
總結
以上是生活随笔為你收集整理的Vue-- $attrs与$listeners的详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zoj-1789
- 下一篇: UVa --10566