props与非props
props属性
使用props进行组件间的数据传输,是单向数据流,即父组件向子组件使用props进行数据传输,子组件只能读取相应的值,但是不能直接对其进行改变
有两种情况可能希望改变props的值
1.传入时作为初始值,在子组件中希望该值作为本地的数据进行使用,在这种情况下,可以将获取的该props值存放到本地data中的一个属性中
props:[title],
data(){
curTitle:this.title
}
2.作为初始值传入,希望对其进行转换。在这种情况下,最好使用props的值定义一个computed属性
props:[title],
computed:{
changeTitle:function(){
return this.title.trim().reserve()
}
}
非props属性,即常见示例class,id,style
- 单根节点
父子件引用子组件时,传入的非props属性,会自动传入子组件根节点上
<propsTest :dataArr="dataArr" id="props-test" class="222" placeholder="请输入"/>
data(){
dataArr:[1,2,3]
}
//propsTest组件
<div>
<h1 v-for="(item,index) in dataArr" :key="index">
{{item}}
</h1>
<input/>
</div>
则父组件的属性会自动添加到子组件的根节点div上
但是有时我们不想将属性传入到根节点,比如placeholder我们希望的是它能够传入到input中
这时,我们需要在子组件中 添加组件选项
inheritAttrs: false,
并在希望将属性传入的元素上使用v-bind="$attrs"
//propsTest组件
<div>
<h1 v-for="(item,index) in dataArr" :key="index">
{{item}}
</h1>
<input v-bind="$attrs"/>
</div>
export default {
name: 'PropsTest',
inheritAttrs: false,
props: {
dataArr: []
},
}
- 多根节点
多个根节点上的 Attribute 继承
与单个根节点组件不同,具有多个根节点的组件不具有自动 attribute 回退行为。如果未显式绑定 $attrs,将发出运行时警告。
<custom-layout id="custom-layout" @click="changeValue"></custom-layout>
// 这将发出警告
app.component('custom-layout', {
template: `
<header>...</header>
<main>...</main>
<footer>...</footer>
`
})
// 没有警告,$attrs被传递到<main>元素
app.component('custom-layout', {
template: `
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
`
})