vue3.0 透传 Attribute

目录

效果一(子组件只有一个根节点,透传生效)

效果二(子组件有多个根节点,透传未生效,且控制台会抛出警告)

效果三(子节点如果不是单根节点的时候,可以通过添加:="$attrs"属性进行透传)

效果四(子节点是单根节点,但是不希望进行透传,inheritAttrs设置为false即不接收属性的透传)


透传是vue中一种特性,“透传 attribute”指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者 v-on 事件监听器。最常见的例子就是 class、style 和 id。


透传特性:

  • 透传的属性只会直接传给单根节点的组件,如果子组件有多个根节点,透传属性不会生效且控制台会抛出警告
  • 透传过去的属性ID获取需要在dom节点加载结束进行,否则获取不到
  • 透传属性命名和子组件上的重复,属性值不会生效

效果一(子组件只有一个根节点,透传生效)

子组件 son.vue

<template>
  <button class="btn-style">btn</button>
</template>

父组件 home.vue

<template>
  <son class="home-style"/>
</template>

<script>
import sonfrom '@/components/son.vue'

export default {
  name: 'HomeView',
  components: {
    son
  }
}
</script>

结果:

<button class="btn-style home-style">btn</button>


效果二(子组件有多个根节点,透传未生效,且控制台会抛出警告)

子组件 son.vue

<template>
  <button class="btn-style">btn1</button>
  <button class="btn-style">btn2</button>
</template>

父组件 home.vue

<template>
  <son class="home-style"/>
</template>

<script>
import sonfrom '@/components/son.vue'

export default {
  name: 'HomeView',
  components: {
    son
  }
}
</script>

结果:

<button class="btn-style">btn</button>

<button class="btn-style">btn</button>


效果三(子节点如果不是单根节点的时候,可以通过添加:="$attrs"属性进行透传)

子组件 son.vue

<template>
  <button class="btn-style">btn1</button>
  <button class="btn-style" :="$attrs">btn2</button>
</template>

 父组件 home.vue

<template>
  <son class="home-style"/>
</template>

<script>
import sonfrom '@/components/son.vue'

export default {
  name: 'HomeView',
  components: {
    son
  }
}
</script>

 结果:

<button class="btn-style">btn1</button>

<button class="btn-style home-style">btn2</button>


效果四(子节点是单根节点,但是不希望进行透传,inheritAttrs设置为false即不接收属性的透传)

子组件 son.vue

<template>
  <button class="btn-style">btn</button>
</template>


<script>
export default {
  inheritAttrs: false,
};
</script>

父组件 home.vue 

<template>
  <son class="home-style"/>
</template>

<script>
import sonfrom '@/components/son.vue'

export default {
  name: 'HomeView',
  components: {
    son
  }
}
</script>

结果:

 <button class="btn-style">btn</button>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web Erek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值