樣式
Nuxt 在樣式方面高度靈活。你可以編寫自己的樣式,或引用本地和外部樣式表。你可以使用 CSS 預處理器、CSS 框架、UI 庫和 Nuxt 模組來設定應用程式的樣式。
本地樣式表
如果你正在編寫本地樣式表,最自然的位置是 app/assets/
目錄。
在元件中匯入
你可以直接在頁面、佈局和元件中匯入樣式表。你可以使用 JavaScript 匯入或 CSS@import
語句.
<script>
// Use a static import for server-side compatibility
import '~/assets/css/first.css'
// Caution: Dynamic imports are not server-side compatible
import('~/assets/css/first.css')
</script>
<style>
@import url("~/assets/css/second.css");
</style>
CSS 屬性
你還可以使用 Nuxt 配置中的 css
屬性。樣式表的自然位置是 app/assets/
目錄。然後你可以引用它的路徑,Nuxt 會將其包含到應用程式的所有頁面中。
export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
})
使用字型
將你的本地字型檔案放在 public/
目錄中,例如在 public/fonts
中。然後你可以在樣式表中透過 url()
引用它們。
@font-face {
font-family: 'FarAwayGalaxy';
src: url('/fonts/FarAwayGalaxy.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
然後透過名稱在你的樣式表、頁面或元件中引用你的字型
<style>
h1 {
font-family: 'FarAwayGalaxy', sans-serif;
}
</style>
透過 NPM 分發的樣式表
你還可以引用透過 npm 分發的樣式表。讓我們以流行的 animate.css
庫為例。
npm install animate.css
yarn add animate.css
pnpm install animate.css
bun install animate.css
然後你可以直接在頁面、佈局和元件中引用它
<script>
import 'animate.css'
</script>
<style>
@import url("animate.css");
</style>
該包也可以作為字串在 Nuxt 配置的 css 屬性中引用。
export default defineNuxtConfig({
css: ['animate.css'],
})
外部樣式表
你可以在 nuxt.config 檔案的 head 部分新增一個 link 元素,將外部樣式表包含在你的應用程式中。你可以透過不同的方法實現這個結果。請注意,本地樣式表也可以透過這種方式包含。
你可以使用 Nuxt 配置的 app.head
屬性來操作 head
export default defineNuxtConfig({
app: {
head: {
link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }],
},
},
})
動態新增樣式表
你可以使用 useHead 可組合函式來在程式碼中動態設定 head 中的值。
useHead({
link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }],
})
Nuxt 內部使用 unhead
,你可以參考其完整文件.
使用 Nitro 外掛修改渲染的 Head
如果你需要更高階的控制,你可以使用鉤子攔截渲染的 html,並以程式設計方式修改 head。
在 ~/server/plugins/my-plugin.ts
中建立這樣的外掛
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook('render:html', (html) => {
html.head.push('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">')
})
})
外部樣式表是渲染阻塞資源:它們必須在瀏覽器渲染頁面之前載入和處理。包含不必要的大型樣式的網頁需要更長的時間才能渲染。你可以在web.dev.
使用預處理器
要使用 SCSS、Sass、Less 或 Stylus 等預處理器,請先安裝它們。
npm install -D sass
npm install -D less
npm install -D stylus
編寫樣式表的自然位置是 app/assets
目錄。然後,你可以使用預處理器的語法將原始檔匯入到你的 app.vue
(或佈局檔案)中。
<style lang="scss">
@use "~/assets/scss/main.scss";
</style>
或者,你可以使用 Nuxt 配置的 css
屬性。
export default defineNuxtConfig({
css: ['~/assets/scss/main.scss'],
})
如果你需要在預處理檔案中注入程式碼,例如Sass partial帶有顏色變數,你可以透過 Vite 的預處理器選項.
在 app/assets
目錄中建立一些 partials
$primary: #49240F;
$secondary: #E4A79D;
$primary: #49240F
$secondary: #E4A79D
然後在你的 nuxt.config
中
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '@use "~/assets/_colors.scss" as *;',
},
},
},
},
})
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
sass: {
additionalData: '@use "~/assets/_colors.sass" as *\n',
},
},
},
},
})
Nuxt 預設使用 Vite。如果你希望使用 webpack,請參考每個預處理器的 loader文件.
預處理器 Workers(實驗性)
Vite 提供了一個實驗性選項可以加快預處理器的使用速度。
你可以在你的 nuxt.config
中啟用此功能
export default defineNuxtConfig({
vite: {
css: {
preprocessorMaxWorkers: true, // number of CPUs minus 1
},
},
})
單檔案元件(SFC)樣式
Vue 和 SFC 最好的事情之一是它在自然處理樣式方面非常出色。你可以直接在元件檔案的樣式塊中編寫 CSS 或預處理器程式碼,因此你將獲得出色的開發體驗,而無需使用 CSS-in-JS 之類的東西。但是,如果你希望使用 CSS-in-JS,你可以找到支援它的第三方庫和模組,例如pinceau.
你可以參考Vue 文件關於 SFC 中元件樣式的全面參考。
類和樣式繫結
你可以利用 Vue SFC 功能透過 class 和 style 屬性來設定元件樣式。
<script setup lang="ts">
const isActive = ref(true)
const hasError = ref(false)
const classObject = reactive({
'active': true,
'text-danger': false,
})
</script>
<template>
<div
class="static"
:class="{ 'active': isActive, 'text-danger': hasError }"
/>
<div :class="classObject" />
</template>
<script setup lang="ts">
const isActive = ref(true)
const error = ref(null)
const classObject = computed(() => ({
'active': isActive.value && !error.value,
'text-danger': error.value && error.value.type === 'fatal',
}))
</script>
<template>
<div :class="classObject" />
</template>
<script setup lang="ts">
const isActive = ref(true)
const errorClass = ref('text-danger')
</script>
<template>
<div :class="[{ active: isActive }, errorClass]" />
</template>
<script setup lang="ts">
const activeColor = ref('red')
const fontSize = ref(30)
const styleObject = reactive({ color: 'red', fontSize: '13px' })
</script>
<template>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }" />
<div :style="[baseStyles, overridingStyles]" />
<div :style="styleObject" />
</template>
請參考Vue 文件獲取更多資訊。
v-bind
的動態樣式 使用
你可以在樣式塊中使用 v-bind 函式引用 JavaScript 變數和表示式。繫結將是動態的,這意味著如果變數值發生變化,樣式也將更新。
<script setup lang="ts">
const color = ref('red')
</script>
<template>
<div class="text">
hello
</div>
</template>
<style>
.text {
color: v-bind(color);
}
</style>
作用域樣式
scoped 屬性允許你單獨設定元件樣式。使用此屬性宣告的樣式僅適用於此元件。
<template>
<div class="example">
hi
</div>
</template>
<style scoped>
.example {
color: red;
}
</style>
CSS 模組
您可以使用CSS 模組使用 module 屬性。透過注入的 $style
變數訪問它。
<template>
<p :class="$style.red">
This should be red
</p>
</template>
<style module>
.red {
color: red;
}
</style>
預處理器支援
SFC 樣式塊支援預處理器語法。Vite 內建支援 .scss、.sass、.less、.styl 和 .stylus 檔案,無需配置。你只需先安裝它們,它們就可以直接在 SFC 中與 lang 屬性一起使用。
<style lang="scss">
/* Write scss here */
</style>
<style lang="sass">
/* Write sass here */
</style>
<style lang="less">
/* Write less here */
</style>
<style lang="stylus">
/* Write stylus here */
</style>
你可以參考Vite CSS 文件和@vitejs/plugin-vue 文件。對於 webpack 使用者,請參考vue loader 文件.
使用 PostCSS
Nuxt 內建了 postcss。你可以在 nuxt.config
檔案中配置它。
export default defineNuxtConfig({
postcss: {
plugins: {
'postcss-nested': {},
'postcss-custom-media': {},
},
},
})
為了在 SFC 中獲得正確的語法高亮,你可以使用 postcss lang 屬性。
<style lang="postcss">
/* Write postcss here */
</style>
預設情況下,Nuxt 預配置了以下外掛
- postcss-import: 改進
@import
規則 - postcss-url: 轉換
url()
語句 - autoprefixer: 自動新增供應商字首
- cssnano: 壓縮和清除
利用佈局實現多種樣式
如果你需要對應用程式的不同部分進行完全不同的樣式設定,可以使用佈局。為不同的佈局使用不同的樣式。
<template>
<div class="default-layout">
<h1>Default Layout</h1>
<slot />
</div>
</template>
<style>
.default-layout {
color: red;
}
</style>
第三方庫和模組
Nuxt 在樣式方面沒有特定偏好,為你提供了廣泛的選擇。你可以使用任何你想要的樣式工具,例如流行的庫UnoCSS或Tailwind CSS.
社群和 Nuxt 團隊開發了許多 Nuxt 模組,使整合更容易。你可以在網站的模組部分中發現它們。這裡有一些模組可以幫助你入門
- UnoCSS: 即時按需原子 CSS 引擎
- Tailwind CSS: 實用至上 CSS 框架
- Fontaine: 字型度量回退
- Pinceau: 適應性樣式框架
- Nuxt UI: 適用於現代 Web 應用的 UI 庫
- Panda CSS: 在構建時生成原子 CSS 的 CSS-in-JS 引擎
Nuxt 模組為你提供了開箱即用的良好開發體驗,但請記住,如果你最喜歡的工具沒有模組,這並不意味著你不能與 Nuxt 一起使用它!你可以為自己的專案自行配置。根據工具的不同,你可能需要使用 Nuxt 外掛和/或製作自己的模組。如果你製作了,請與社群分享!
輕鬆載入網路字型
您可以使用Nuxt Google Fonts 模組載入 Google Fonts。
如果你正在使用UnoCSS,請注意它帶有一個網路字型預設方便地從常見提供商(包括 Google Fonts 等)載入字型。
高階
過渡
Nuxt 具有與 Vue 相同的 <Transition>
元素,並且還支援實驗性的 View Transitions API。
字型高階最佳化
我們建議使用Fontaine來減少你的CLS。如果你需要更高階的功能,請考慮建立 Nuxt 模組來擴充套件構建過程或 Nuxt 執行時。
LCP 高階最佳化
你可以執行以下操作來加快全域性 CSS 檔案的下載速度
- 使用 CDN,使檔案在物理上更接近你的使用者
- 壓縮你的資產,最好使用 Brotli
- 使用 HTTP2/HTTP3 進行交付
- 在同一個域上託管你的資產(不要使用不同的子域)
如果你使用 Cloudflare、Netlify 或 Vercel 等現代平臺,其中大部分都會自動為你完成。你可以在web.dev.
如果你的所有 CSS 都由 Nuxt 內聯,你可以(實驗性地)完全停止在渲染的 HTML 中引用外部 CSS 檔案。你可以透過鉤子來實現這一點,你可以將它放在模組中,或者放在 Nuxt 配置檔案中。
export default defineNuxtConfig({
hooks: {
'build:manifest': (manifest) => {
// find the app entry, css list
const css = Object.values(manifest).find(options => options.isEntry)?.css
if (css) {
// start from the end of the array and go to the beginning
for (let i = css.length - 1; i >= 0; i--) {
// if it starts with 'entry', remove it from the list
if (css[i].startsWith('entry')) {
css.splice(i, 1)
}
}
}
},
},
})