vue中 v-bind=“$props“和v-bind=“$attrs“的理解和使用方式

文章详细解释了在Vue中v-bind=$attrs用于隔代传值,传递所有未声明为prop的组件属性,而v-bind=$props则用于将父组件的props直接下发到子组件,需在子组件中声明。通过示例展示了当父组件声明或不声明props时,两者在子组件中this.$attrs和this.$props的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、v-bind=“$attrs“

二、v-bind="$props"

三、总结


一、v-bind=“$attrs“

主要用于组件之间的隔代传值。 在一个组件里,this.$attr传递当前组件身上绑定的所有属性(不考虑声明了组件内prop的话)

这么说是不是稍微有点绕?让我们看看例子。

// GrandFather.vue    祖父组件
<template>
   <div>
      <father-page :name="testName" :data-name="dataName" />
    </div>
</template>
<script>
    ...
    testName = 'Test101';
    ...
    dataName = 'dataName'
</script>
// FatherPage.vue    父组件
<template>
  <div>
    <child-page v-bind="$attrs" />
  </div>
</template>
<script>
    // 不声明props(不接收祖父组件传过来的数据)
</script>

这时候ChildPage.vue和FatherPage.vue 组件内的 this.$attrs

如果我们修改一下 FatherPage.vue 组件

// FatherPage.vue    父组件
<template>
  <div>
    <child-page v-bind="$attrs" />
  </div>
</template>
<script>
    ...
    props:['testName']
</script>

 

可以看见FatherPage.vue的 this.$attrs 属性里少了testName,而props多了testName

ChildPage.vue接收到的this.$attrs也只有dataName了。

如果使用的是 v-bind="$props" 呢?咱们继续往下看


二、v-bind="$props"

将父组件的所有props下发给它的子组件,子组件需要在其props:{} 中定义要接受的props。

如果将父组件传递给子组件的方式改为

        <grand-son v-bind="$props"></grand-son>

如果在 FatherPage.vue 的props中接收的是testName,那么通过v-bind="$props" 传递给ChildPage.vue 的 this.$attrs 就是testName,如果在 FatherPage.vue中没有声明props,那么在ChildPage.vue 中的this.$attrs 就是空

                        


三、总结

        v-bind="$props"和v-bind="$attrs" 其实就是往子组件里传的参数不同,一个传的是vm.props一个传的是vm.attrs。而组件的attrs其实就是除了本组件声明的prop属性之外的其他绑定在本组件上的属性(可以是vue的动态绑定属性或者name type这些原生/自定义属性)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值