Vue组件的inheritAttrs属性

2022-07-25,,,

vue官网对于inheritAttrs属性解释:如果你不希望组件的根元素继承特性,你可以在组件的选项中设置 inheritAttrs: false。
可能不是很好理解,我们可以举个例子来验证一下。

当inheritAttrs为false

<div id ="wxApp" class ="appclass"> 
        <blog-post title="标题" demo-one="未定义属性1" demo-tow="未定义属性2" class="cointer2" style="color:red"></blog-post>
    </div>

Vue.component("blog-post",{
            props:{
                title:String,
            },
            inheritAttrs:false,
            template:`<div demo-one="hello" class="cointer" style="width:500px" >
                <h1>title:{{title}}</h1>
            </div>
            `
        })

当inheritAttrs为false时的结果为:自定义的属性不会覆盖组件中属性名称的值

当inheritAttrs为true时的结果为:自定义的属性会插入到组件中,覆盖组件中属性名称的值

但是在自定义组件中插入style和class属性时,不论inheritAttrs值为true或false都不能影响class和style属性传到我们的模板中。如果模板中也有class属性和style属性。则模板中的属性和自定义组件中的属性会组合叠加在一块

$arrts的使用

在我们原代码的基础上给模板里用"v-bind: $arrts"的两种情况
当inheritAttrs值为false时

 Vue.component("blog-post",{
            props:{
                title:String,
            },
            inheritAttrs:false,
            template:`<div demo-one="hello" class="cointer" v-bind=$arrts style="width:500px" >
                <h1>title:{{title}}</h1>
            </div>
            `
        })

当inheritAttrs值为false时,则自定义属性不会覆盖组件中属性名称的值

inheritAttrs=true时

Vue.component("blog-post",{
            props:{
                title:String,
            },
            inheritAttrs:true,
            template:`<div demo-one="hello" class="cointer" style="width:500px" v-bind=$arrts>
                <h1>title:{{title}}</h1>
            </div>
            `
        })

当inheritAttrs值为true时,则自定义属性会覆盖组件中属性名称的值

本文地址:https://blog.csdn.net/weixin_49868928/article/details/111935639

《Vue组件的inheritAttrs属性.doc》

下载本文的Word格式文档,以方便收藏与打印。