Vue 学院 #1:作用域样式

2025-06-04

Vue 学院 #1:作用域样式

欢迎来到首届 Vue 学院!这里会列出很多关于 Vue 的文章!我在这方面有两年半的经验,可以教一些这方面的知识!

在本课程中,我们将重点关注scopedCSS 中的属性。

一个简单的例子:

<style>
    .toto {
        color: blue;
    }
</style>

<template>
    <div class='toto'> Hi </div>
</template>
Enter fullscreen mode Exit fullscreen mode

为什么它不好

它可以正常工作,但你的类可以在任何其他组件中使用。因此,如果你更改toto类,可能会影响其他组件的样式(side effect)。

如果您想声明通用类,您应该为此创建一个适当的文件。

解决方案

创建只能由一个组件使用的类的解决方案是scoped中的属性<style>

<style scoped>
    .toto {
        color: blue;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

CSS 将应用于当前组件的元素only。这类似于 中的样式封装Shadow DOM

它是如何深入工作的

当你编译代码时,上面的代码将等于

<style>
    .toto[data-v-f3f3eg9] {
        color: blue;
    }
</style>

<template>
    <div class='toto' data-v-f3f3eg9> Hi </div>
</template>
Enter fullscreen mode Exit fullscreen mode

正如你所见,它非常简单基础,但功能非常强大。Vue 会在 上注入一个属性,并将此属性应用于每个包含! 的scoped class元素。scoped class


我希望你喜欢这篇文章!

🎁 如果您在TwitterUnderrated skills in javascript, make the difference上关注我并给我点赞,即可免费获得我的新书😁

或者在这里获取

🎁我的新闻通讯

☕️ 你可以支持我的作品🙏

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/code__oz

👨‍💻 Github:https://github.com/Code-Oz

你也可以标记🔖这篇文章!

文章来源:https://dev.to/codeoz/vue-academy-1-scoped-style-5g0e
PREV
Vue 学院 #5:组件之间的通信
NEXT
2.5 年经验总结的 6 个 VueJs 基本技巧 #1