Vue中inheritAttrs的使用例項詳解
阿新 • • 發佈:2021-01-04
今天舉一個例子解釋一下inheritAttrs的使用
先看程式碼
<body> <div id="app" class="vueclass"> <my-com title="標題" wx-attr1="未定義屬性1" wx-attr2="未定義屬性2"></my-com> </div> <script type="text/javascript"> Vue.component("my-com",{ props:{ title:String,},inheritAttrs:false,template:` <div wx-attr1="hello" > <h1>{{title}}</h1> </div> `,}) const App = new Vue({ el:"#app",data:{ },methods:{ } }) </script> </body>
當inheritAttrs的值為false時,自定義屬性是插入不到我們的元件中的,結果如下
當inheritAttrs的值為true時,自定義屬性可以插入到我們的元件中,並且會覆蓋掉在元件中相同未定義屬性名稱的值,結果如下
但在元件中定義的class屬性和style屬性,使用inheritAttrs屬性並不能阻礙class屬性和style屬性傳到模板中,如果模板中也存在class屬性和style屬性,這樣屬性會疊加到一起
結果如下
還有一種情況,先看程式碼
<body> <div id="app" class="vueclass"> <my-com title="標題" wx-attr1="未定義屬性1" wx-attr2="未定義屬性2" class="wxClass" style="color:red"></my-com> </div> <script type="text/javascript"> Vue.component("my-com",inheritAttrs:,template:` <div wx-attr1="hello" class="div1" style="width:500px" v-bind="$attrs"> <h1>{{title}}</h1> </div> `,methods:{ } }) </script> </body>
當模板裡繫結v-bind="$attrs"時,inheritAttrs為true時,自定義屬性可以插入到我們的元件中,並且會覆蓋掉在元件中相同未定義屬性名稱的值,結果如下
當模板裡繫結v-bind="$attrs"時,inheritAttrs為false時,自定義屬性可以插入到我們的元件中,但不會覆蓋掉在元件中相同未定義屬性名稱的值,結果如下
當模板裡繫結v-bind="$attrs"時,並不會影響class屬性與style屬性,元件裡的值依然會疊加到模板裡
到此這篇關於Vue中inheritAttrs的使用的文章就介紹到這了,更多相關Vue inheritAttrs使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!