vue3-深入组件-透传属性

透传属性 (透传 attribute)

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

属性继承

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

// 组件

import { ref } from 'vue'




.container {
}

// 父组件

import { ref } from 'vue'
import Com16 from '@/components/demo/Com16.vue'



.container {
}

vue3-深入组件-透传属性_第1张图片

对 class 和 style 的合并

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

// 子组件中
这是深入组件-属性透传

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

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

//子组件

import { ref } from 'vue'

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




.container {
}

//父组件

import { ref } from 'vue'
import Com16 from '@/components/demo/Com16.vue'
const fun2 = () => {
  console.log('我是父组件事件')
}



.container {
}

vue3-深入组件-透传属性_第2张图片

禁用 Attributes 继承

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

inheritAttrs: false。


defineOptions({
  inheritAttrs: false
})
import { ref } from 'vue'

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

确实 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

如果需要,你可以在   

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

你可能感兴趣的:(vue3,vue.js,javascript,前端,vue)