样式方案
Nuxt 对样式方案几乎不设限:纯 CSS、预处理器、Tailwind / UnoCSS,或 CSS Modules —— 都是“一等公民”。
本地样式文件
把源文件放进 app/assets/,任何组件里都能引用:
<script>
import '~/assets/css/first.css'
</script>
<style>
@import url("~/assets/css/second.css");
</style>
要全局注入,直接在 nuxt.config.ts 中声明:
export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
})
全局 CSS 会被内联到 SSR HTML,首屏一上来就是带样式的。
外部样式表
从配置里挂 <link>:
export default defineNuxtConfig({
app: {
head: {
link: [
{ rel: 'stylesheet', href: 'https://cdn.example.com/reset.css' },
],
},
},
})
或通过 useHead 动态挂载:
<script setup lang="ts">
useHead({
link: [{ rel: 'stylesheet', href: 'https://cdn.example.com/theme.css' }],
})
</script>
外部样式表会阻塞渲染,能本地化时尽量本地化。
预处理器(SCSS / Sass / Less / Stylus)
安装预处理器后 Vite 会自动识别:
pnpm add -D sass
<style lang="scss">
@use "~/assets/scss/main.scss";
</style>
或全局注册:
export default defineNuxtConfig({
css: ['~/assets/scss/main.scss'],
})
想要每个文件都自动注入变量、设计 token?用 Vite 的 preprocessorOptions:
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: { additionalData: '@use "~/assets/_colors.scss" as *;' },
},
},
},
})
单文件组件样式
这正是 Vue 的强项:
<script setup lang="ts">
const isActive = ref(true)
const color = ref('crimson')
</script>
<template>
<div :class="['box', { active: isActive }]">
<p :style="{ color }">hello</p>
</div>
</template>
<style scoped>
.box { padding: 1rem; }
.active { outline: 2px solid v-bind(color); }
</style>
几个关键特性:
scoped—— 样式只作用于本组件。v-bind()—— 在<style>中使用响应式值。module—— CSS Modules,通过$style访问:
<template>
<p :class="$style.red">red</p>
</template>
<style module>
.red { color: red; }
</style>
lang="scss"(或sass、less、stylus)—— 每个<style>块独立选择预处理器。
PostCSS
Nuxt 已经预配置了 postcss-import、postcss-url、autoprefixer、cssnano。要添加其他插件:
export default defineNuxtConfig({
postcss: {
plugins: {
'postcss-nested': {},
'postcss-custom-media': {},
},
},
})
SFC 里用 <style lang="postcss"> 可以获得正确的语法高亮。
Tailwind CSS / UnoCSS
想用 utility-first 方案,官方模块是最快路径:
pnpm add -D @nuxtjs/tailwindcss
export default defineNuxtConfig({
modules: ['@nuxtjs/tailwindcss'],
})
或 UnoCSS:
pnpm add -D @unocss/nuxt
export default defineNuxtConfig({
modules: ['@unocss/nuxt'],
})
两者都会自动注入生成的 CSS,不需要手动 import 'uno.css'。
用布局做风格分隔
当应用里不同区域风格差别很大(比如深色后台 vs 亮色营销页),把外壳拆到布局里最干净:
<!-- app/layouts/admin.vue -->
<template>
<div class="admin-shell"><slot /></div>
</template>
<style>
.admin-shell { background: #0f172a; color: #e2e8f0; }
</style>
策略选择
| 需求 | 选什么 |
|---|---|
| 工具类 + 小团队 | Tailwind / UnoCSS |
| 组件级隔离 | <style scoped> |
| 彻底避免类名冲突 | <style module> |
| 设计系统 + 设计 token | SCSS + additionalData |
| 可定制主题 | app.config + CSS 变量 |
没有所谓“标准答案”,Nuxt 允许你在同一个项目里混着用。