vue实现单独样式
Vue 实现单独样式的方法
使用 scoped 样式
在单文件组件(.vue 文件)的 <style> 标签中添加 scoped 属性,样式仅作用于当前组件。Vue 会通过添加唯一属性(如 data-v-xxxxxx)实现样式隔离。
<template>
<div class="example">仅当前组件生效</div>
</template>
<style scoped>
.example {
color: red;
}
</style>
使用 CSS Modules
通过 module 属性启用 CSS Modules,生成的类名会被哈希化避免冲突。需通过 $style 对象引用类名。
<template>
<div :class="$style.example">哈希类名样式</div>
</template>
<style module>
.example {
background: blue;
}
</style>
动态类名绑定
结合 Vue 的 :class 绑定,根据条件动态切换样式类。
<template>
<div :class="{ active: isActive }">动态样式</div>
</template>
<script>
export default {
data() {
return { isActive: true }
}
}
</script>
<style>
.active {
font-weight: bold;
}
</style>
深度选择器 (>>> 或 ::v-deep)
穿透 scoped 限制,修改子组件样式(需谨慎使用)。
<style scoped>
.parent ::v-deep .child {
padding: 10px;
}
</style>
内联样式
通过 :style 绑定行内样式,适合动态样式场景。
<template>
<div :style="{ color: textColor }">内联样式</div>
</template>
<script>
export default {
data() {
return { textColor: 'green' }
}
}
</script>
全局样式与局部混合
在 main.js 或单独 CSS 文件中定义全局样式,组件内通过普通 <style> 补充局部样式。
/* global.css */
body {
margin: 0;
}
<style>
/* 组件内全局样式 */
</style>
<style scoped>
/* 组件内局部样式 */
</style>






