19、Vue 3 (2024 版)基础笔记 - 透传 Attributes

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 81

时间: 2024-05-19 03:08:35

“透传 attribute” 指的是传递属性给一个组件,却没有被该组件声明为 propsemits 的 attribute 或者 v-on 事件监听器。最常见的例子就是 classstyleid

Attributes 继承

1、父组件

src/App.vue

<template>
    <!-- 定义一个属性 -->
    <SearchComp class="ziruchu"/>

</template>

<script setup lang="ts">
    import SearchComp from "./components/comp/SearchComp.vue";
</script>
2、子组件

src/components/comp/SearchComp.vue

<template>
    <div>
        <p>搜索</p>
    </div>
</template>

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

<style scoped>
    /* 类属性 */
    .ziruchu {
        background-color: lightcyan;
    }
</style>

此时,类的样式是生效的。

当且仅当组件中只有一个根元素时,透传属性才会生效。

需要注意的是,当组件中存在多个根据元素时,透传样式失效,如下:

<template>
    <div>
        <p>搜索</p>
    </div>

    <div>
         <!-- 你猜,span 会不会有类样式生效 -->
         <span>你猜,这个元素,类样式会不会生效?</span>
    </div>
</template>

<script setup lang="ts">
</script>

<style scoped>
    /* 类属性 */
    .ziruchu {
        background-color: lightcyan;
    }
</style>

禁用 Attributes 继承

src/components/comp/SearchComp.vue

<template>
    <div>
        <p>搜索</p>
    </div>
</template>

<script setup lang="ts">
    defineOptions({
        // 禁用透传样式
        inheritAttrs:false
    })
</script>

<style scoped>
    .ziruchu {
        background-color: lightcyan;
    }
</style>
请登录后再评论