vue制作css
Vue 中编写 CSS 的常用方法
1. 内联样式
直接在 Vue 模板的标签中使用 :style 绑定动态或静态样式。
<template>
<div :style="{ color: textColor, fontSize: fontSize + 'px' }">内联样式示例</div>
</template>
<script>
export default {
data() {
return {
textColor: 'red',
fontSize: 16
};
}
};
</script>
2. Scoped CSS
在单文件组件(.vue)的 <style> 标签中添加 scoped 属性,使样式仅作用于当前组件。
<template>
<div class="scoped-example">Scoped CSS 示例</div>
</template>
<style scoped>
.scoped-example {
color: blue;
margin: 10px;
}
</style>
3. CSS Modules
通过配置构建工具(如 Webpack),将类名转换为唯一哈希值,避免全局污染。

<template>
<div :class="$style.moduleExample">CSS Modules 示例</div>
</template>
<style module>
.moduleExample {
background-color: #f0f0f0;
padding: 12px;
}
</style>
4. 预处理器支持
Vue 支持 Sass、Less、Stylus 等预处理器,需安装对应依赖。
<style lang="scss">
$primary-color: #42b983;
.preprocessor-example {
color: $primary-color;
}
</style>
5. 全局样式
在项目的入口文件(如 main.js)或公共 CSS 文件中定义全局样式。

/* global.css */
.global-style {
font-family: 'Arial', sans-serif;
}
在 main.js 中引入:
import './assets/global.css';
6. 动态类名绑定
使用 :class 绑定动态类名,结合对象或数组语法。
<template>
<div :class="{ active: isActive, 'text-danger': hasError }">动态类名示例</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
};
}
};
</script>
注意事项
- Scoped CSS 原理:通过添加
data-v-xxx属性实现样式隔离,但深度选择器(如/deep/或::v-deep)可穿透作用域。 - 性能优化:避免过度使用内联样式,优先选择 Scoped CSS 或 CSS Modules。
- 响应式设计:结合 CSS 变量(Custom Properties)实现动态主题切换。
示例:响应式主题切换
<template>
<div class="theme-container" :style="{'--primary-color': primaryColor}">
主题颜色示例
</div>
</template>
<script>
export default {
data() {
return {
primaryColor: '#42b983'
};
}
};
</script>
<style>
.theme-container {
color: var(--primary-color);
}
</style>






