props与非props的属性

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

  1. 单根节点
    父子件引用子组件时,传入的非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: []
  },
}

在这里插入图片描述

  1. 多根节点
    多个根节点上的 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>
  `
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值