1.非props属性的了解
尽管为组件定义明确的 props是推荐的传参方式,组件的作者却并不总能预见到组件被使用的场景。
所以,组件可以接收任意传入的特性,这些特性都会被添加到组件的根元素上。
简单的说就是父组件可以在使用子组件的时候给子组件传递n多的属性, 只有子组件使用props接受的才会成为子组件的参数, 没有通过props声明的属性就是非props, 这些属性会自动添加为子组件根标签的属性.
示例如下:
<div id="app">
<father-com></father-com>
</div>
<!-- 定义子组件模板-->
<template id="son">
<div>
{{msg}}
</div>
</template>
<!--d定义父组件模板-->
<template id="father">
<div>
<son-com
:msg = "msg"
:title="title"
> </son-com>
</div>
</template>
<script>
//非props就是子组件并没有明确props来接受父组件的传值,那么在网页中子组件传值的属性将会成为标签的私有属性
let SonCom = ({
props:["msg"],
template:"#son",
})
let FatherCom = ({
template:"#father",
data(){
return{
msg:"你好,世界!",
title:"标题"
}
},
components:{
SonCom,
}
})
let vm = new Vue({
el:"#app",
components: {
FatherCom,
}
})
</script>
子组件的 props
中没有接受的 title
属性变成了子组件根标签的属性.
总结:
非props就是子组件并没有明确props来接受父组件的传值,那么在网页中子组件传值的属性将会成为标签的私有属性
上面一个例子,了解到如果父组件给子组件传递非prop属性,会自动成为子组件模板中根标签的标签属性, 适用于任何HTML属性或特性,
可是如果父组件传递的非prop属性与子组件的根标签的属性重名了怎么办呢?
会发生两种情况, 一,替换,二合并, 先来看看替换的情况
1.1 非props属性替换
如果父组件传递的prop属性与子组件的根标签的属性重名,大部分情况会覆盖子组件根标签上的同名属性. 即替换效果.
<div id="app">
<father-com></father-com>
</div>
<!-- 定义子组件模板-->
<template id="son">
<!-- 子组件根标签的type属性值text 被父组件传递过了的非prop type属性值 color替换了 -->
<input type="text" />
</template>
<!--d定义父组件模板-->
<template id="father">
<div>
<!-- 父组件向子组件传递非prop属性 type 值为color -->
<son-com
:type="type"
> </son-com>
</div>
</template>
<script>
let SonCom = ({
template:"#son",
})
let FatherCom = ({
template:"#father",
data(){
return{
type: 'color',
}
},
components:{
SonCom,
}
})
let vm = new Vue({
el:"#app",
components: {
FatherCom,
}
})
</script>
通过上面的这个简单的小例子,我们就可以发现:子组件跟标签的 type
属性值 text
被父组件传递过来的非 props
的 type
的值 color
替换了
这样的效果非常不好,可能会破坏子组件. 所以一定要注意.
1.2 非props属性的和并
当然了大部分会发生替换, 但是也有两个特殊的属性,会发生合并的效果,这两个属性就是 class
与style
属性
看下面的代码:
<div id="app">
<father-com></father-com>
</div>
<!-- 定义子组件模板-->
<template id="son">
<div>
{{msg}}
</div>
</template>
<!--d定义父组件模板-->
<template id="father">
<div>
<son-com
:msg = "msg"
:class ="className"
:style="style"
> </son-com>
</div>
</template>
<script>
//非props就是子组件并没有明确props来接受父组件的传值,那么在网页中子组件传值的属性将会成为标签的私有属性
let SonCom = ({
props:["msg"],
template:"#son",
})
let FatherCom = ({
template:"#father",
data(){
return{
className:"box",
style:{
width:"300px",
height:"200px",
backgroundColor:"#58a",
}
}
},
components:{
SonCom,
}
})
let vm = new Vue({
el:"#app",
components: {
FatherCom,
}
})
</script>
在这段代码中非 props
属性 style
和 class
与原属性进行了和并, 与子组件根标签的class 和 style 属性发生合并.