vue3-深入组件-透传属性

透传属性 (透传 attribute)

什么是透传属性(透传 attribute)? 传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者是事件监听器,例如 class style id 等。

属性继承

当一个组件以单个元素作渲染时,透传的属性会自动被添加到根元素上。

// 组件
<script lang="ts" setup>
import { ref } from 'vue'
</script>

<template>
  <div class="container">
    <h1>这是深入组件-属性透传</h1>
  </div>
</template>

<style lang="scss" scoped>
.container {
}
</style>


// 父组件
<script lang="ts" setup>
import { ref } from 'vue'
import Com16 from '@/components/demo/Com16.vue'
</script>

<template>
  <div class="container">
    <Com16 class="big"></Com16>
  </div>
</template>

<style lang="scss" scoped>
.container {
}
</style>


对 class 和 style 的合并

如果一个子组件的根元素已经有了 class 或 style attribute,它会和从父组件上继承的值合并。

// 子组件中
<h1 class="h111">这是深入组件-属性透传</h1>

同样的规则也适用于 v-on 事件监听器

当父子组件都定义了事件则都会出发,并且是从内到外相应

//子组件
<script lang="ts" setup>
import { ref } from 'vue'

const fun1 = () => {
  console.log('我是组件事件')
}
</script>

<template>
  <div class="container h1">
    <h1 @click="fun1">这是深入组件-属性透传</h1>
  </div>
</template>

<style lang="scss" scoped>
.container {
}
</style>

//父组件
<script lang="ts" setup>
import { ref } from 'vue'
import Com16 from '@/components/demo/Com16.vue'

const fun2 = () => {
  console.log('我是父组件事件')
}
</script>

<template>
  <div class="container">
    <Com16 @click="fun2" class="big"></Com16>
  </div>
</template>

<style lang="scss" scoped>
.container {
}
</style>

禁用 Attributes 继承

如果你不想要一个组件自动地继承 attribute,你可以在组件选项中设置

inheritAttrs: false。

<script lang="ts" setup>
defineOptions({
  inheritAttrs: false
})
import { ref } from 'vue'

const fun1 = () => {
  console.log('我是组件事件')
}
</script>

确实 class 没有 big 了

这些透传进来的 attribute 可以在模板的表达式中直接用 $attrs 访问到。

template Fallthrough attribute: {{ $attrs }} 这个 $attrs 对象包含了除组件所声明的 props 和 emits 之外的所有其他 attribute,例如 class,style,v-on 监听器等等。

注意:

  • 和 props 有所不同,透传 attributes 在 JavaScript 中保留了它们原始的大小写,所以像 foo-bar 这样的一个 attribute 需要通过 $attrs['foo-bar'] 来访问。

  • 像 @click 这样的一个 v-on 事件监听器将在此对象下被暴露为一个函数 $attrs.onClick。

多根节点的 Attributes 继承

和单根节点组件有所不同,有着多个根节点的组件没有自动 attribute 透传行为。如果 $attrs 没有被显式绑定,将会抛出一个运行时警告。

在 JavaScript 中访问透传 Attributes

如果需要,你可以在 <script setup> 中使用 useAttrs() API 来访问一个组件的所有透传 attribute:

<script setup>
import { useAttrs } from 'vue'

const attrs = useAttrs()
</script>
  

需要注意的是,虽然这里的 attrs 对象总是反映为最新的透传 attribute,但它并不是响应式的 (考虑到性能因素)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值