contentstack
nuxt-contentstack

用於 Nuxt 的 Contentstack 整合

Nuxt Contentstack

Nuxt Contentstack

npm versionnpm downloadsLicenseNuxt

用於 Nuxt 的 Contentstack 整合。

注意:這是一個由 @timbenniks 維護的 OSS 專案,**不是**由 Contentstack 團隊官方維護的包。支援請求可以透過 Github issues 和直接渠道聯絡 @timbenniks。

功能

  • ⚡️ 輕鬆設定
  • ⚡️ Contentstack 的完整 Vue 可組合項集合
  • ⚡️ 透過高階篩選查詢條目和資產
  • ⚡️ 高階篩選和分頁
  • ⚡️ 帶有響應式 URL 的影像轉換
  • ⚡️ @nuxt/image 整合,自動最佳化
  • ⚡️ 即時預覽和視覺化構建器
  • ⚡️ 個性化支援
  • ⚡️ 帶有完整型別安全的 TypeScript 支援
  • ⚡️ 暴露的 SDK:TS Delivery SDK、Live Preview Utils SDK、Personalize SDK

快速設定

透過一個命令將模組安裝到您的 Nuxt 應用中

npx nuxi module add nuxt-contentstack

或者:新增到 nuxt.config.ts

modules: ['nuxt-contentstack'],

'nuxt-contentstack': {
  // Required core settings
  apiKey: 'your_contentstack_api_key',
  deliveryToken: 'your_delivery_token',
  environment: 'your_environment',

  // Optional settings with smart defaults
  region: 'eu',
  branch: 'main',
  locale: 'en-us',

  // Live Preview
  livePreview: {
    enable: true,
    previewToken: 'your_preview_token', // no need for preview token if you are not using live preview
    editableTags: true,
    editButton: true
  },

  // Personalization
  personalization: {
    enable: true,
    projectUid: 'your_project_uid'
  },

  debug: true
},

選項

核心設定(必填)

  • apiKey - 您的 Contentstack 堆疊 API 金鑰(以“blt”開頭)
  • deliveryToken - 您的 Contentstack 交付令牌(以“cs”開頭)
  • environment - 目標環境(“preview”|“production”)

核心設定(可選)

  • region - Contentstack 區域:“us”|“eu”|“au”|“azure-na”|“azure-eu”|“gcp-na”|“gcp-eu”(預設值:“us”)
  • branch - 內容分支(預設值:“main”)
  • locale - 預設語言環境(預設值:“en-us”)

即時預覽設定

配置 livePreview 物件,包含:

  • enable - 啟用即時預覽模式
  • previewToken - Contentstack 的預覽令牌(以“cs”開頭,如果啟用則為必填)
  • editableTags - 新增可編輯標籤以進行視覺化構建(也控制自動 CSLP 屬性清理)
  • editButton - 啟用編輯按鈕(布林值或詳細配置物件)
  • mode - 即時預覽模式:“builder”|“preview”(預設值:“builder”)
  • ssr - 啟用 SSR 模式(實驗性,預設值:false)

個性化設定

配置 personalization 物件,包含:

  • enable - 啟用個性化功能
  • projectUid - 您的個性化專案 UID(在 Contentstack UI 中找到)

通用設定

  • debug - 啟用除錯日誌和配置轉儲

個性化示例

// get Personalize SDK
const { Personalize } = useNuxtApp().$contentstack;

// set attribute
await Personalize.set({ age: 20 });

// trigger impression
// experienceShortId to be found on the experiences list page in contentstack
experienceShortId = 0;
await Personalize.triggerImpression(experienceShortId);

// trigger conversion event
// 'eventKey' can be found when creatign an event in Contentstack Personalize
await Personalize.triggerEvent("eventKey");

提供

此模組提供一個 $contentstack 物件,包含:

  • stack:來自 Delivery SDK 的 Stack 物件。使用它查詢所有內容。
  • ContentstackLivePreview:Live Preview Utils SDK 的例項。
  • livePreviewEnabled:是否啟用了即時預覽?
  • editableTags:我們是否需要用於視覺化構建的可編輯標籤?
  • Personalize:Personalize SDK 的例項。
  • variantAlias:要傳遞給 Delivery SDK 的變體清單。
const {
  editableTags,
  stack,
  livePreviewEnabled,
  ContentstackLivePreview,
  Personalize,
  variantAlias,
  VB_EmptyBlockParentClass,
} = useNuxtApp().$contentstack;

元件

此模組為常見的 Contentstack 用例提供了 Vue 元件。

ContentstackModularBlocks

一個靈活、通用的元件,用於將 Contentstack 模組塊渲染為 Vue 元件。非常適合動態頁面佈局、元件庫和內容驅動的 UI。

功能

  • 自動元件對映 - 自動將 Contentstack 塊型別對映到 Vue 元件
  • 自動獲取能力 - 可以自動獲取條目資料並提取塊(新功能)
  • 靈活的資料結構 - 支援各種 Contentstack 模組塊格式
  • 即時預覽就緒 - 全面支援 Contentstack 即時預覽,帶有 data-cslp 屬性
  • 視覺化構建器支援 - 包含用於視覺化構建的空狀態類
  • TypeScript 支援 - 帶有泛型的全面型別定義
  • SSR 相容 - 在伺服器上完美渲染並無縫水合
  • 可定製樣式 - 可配置的 CSS 類和容器屬性
  • 錯誤處理 - 未對映元件的優雅回退
  • 插槽支援 - 透過插槽實現自定義載入、錯誤和空狀態內容

使用模式

該元件支援兩種使用模式,以實現最大的靈活性

模式 1:自動獲取條目 + 渲染塊(新功能)

非常適合簡單的頁面渲染 - 只需提供條目詳細資訊,讓元件處理所有事情

<script setup>
import Hero from "./components/Hero.vue";
import Grid from "./components/Grid.vue";
import TextBlock from "./components/TextBlock.vue";

// Map Contentstack block types to Vue components
const componentMapping = {
  hero: Hero,
  grid: Grid,
  text_block: TextBlock,
};
</script>

<template>
  <!-- Component fetches entry and renders blocks automatically -->
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    blocks-field-path="components"
    :reference-field-path="['blocks.block.image']"
    :json-rte-path="['rich_text', 'blocks.block.copy']"
    locale="en-us"
    :component-map="componentMapping"
  >
    <!-- Custom loading state -->
    <template #loading>
      <div class="loading-spinner">Loading page content...</div>
    </template>

    <!-- Custom error state -->
    <template #error>
      <div class="error-message">Failed to load content</div>
    </template>
  </ContentstackModularBlocks>
</template>

模式 2:傳統模式,帶預取塊

當您需要對資料獲取有更多控制時使用

<script setup>
import Hero from "./components/Hero.vue";
import Grid from "./components/Grid.vue";
import TextBlock from "./components/TextBlock.vue";

// Map Contentstack block types to Vue components
const componentMapping = {
  hero: Hero,
  grid: Grid,
  text_block: TextBlock,
};

// Fetch your page data manually
const { data: page } = await useGetEntryByUrl({
  contentTypeUid: "page",
  url: useRoute().path,
});
</script>

<template>
  <!-- Pass pre-fetched blocks -->
  <ContentstackModularBlocks
    :blocks="page.components"
    :component-map="componentMapping"
  />
</template>

高階用法

<script setup>
import Hero from "./blocks/Hero.vue";
import Grid from "./blocks/Grid.vue";
import DefaultBlock from "./blocks/DefaultBlock.vue";

const componentMapping = {
  hero: Hero,
  grid: Grid,
  text_section: TextSection,
  image_gallery: ImageGallery,
};
</script>

<template>
  <ContentstackModularBlocks
    :blocks="page.modular_blocks"
    :component-map="componentMapping"
    :fallback-component="DefaultBlock"
    :auto-extract-block-name="true"
    :show-empty-state="true"
    container-class="page-blocks"
    empty-block-class="visual-builder__empty-block-parent"
    empty-state-message="No content blocks available"
    key-field="_metadata.uid"
    block-name-prefix="block_"
    :container-props="{ 'data-page-id': page.uid }"
  >
    <!-- Custom empty state -->
    <template #empty>
      <div class="custom-empty-state">
        <h3>No content blocks found</h3>
        <p>Please add some content in Contentstack</p>
      </div>
    </template>
  </ContentstackModularBlocks>
</template>

屬性

核心屬性

屬性型別預設描述
blocksContentstackBlock[][]Contentstack 模組塊陣列
componentMapComponentMapping{}將塊型別對映到 Vue 元件的物件
fallbackComponentComponent | stringContentstackFallbackBlock未對映塊型別的回退元件

自動獲取屬性(新功能)

屬性型別預設描述
contentTypeUidstring未定義用於獲取條目的內容型別 UID
urlstring未定義透過 URL 獲取條目
referenceFieldPathstring[][]要包含的引用欄位路徑
jsonRtePathstring[][]JSON RTE 欄位路徑
localestring'en-us'條目的語言環境
replaceHtmlCslpbooleanfalse替換 HTML CSLP 標籤
blocksFieldPathstring'components'從中提取模組塊的欄位路徑
seoMetaSeoMetaInput未定義SEO 元資料物件(直接傳遞給 useSeoMeta)
autoSeoMetaboolean | Record<string, string>false從條目資料自動生成 SEO

樣式屬性

屬性型別預設描述
containerClassstring'contentstack-modular-blocks'容器的 CSS 類
emptyBlockClassstring'visual-builder__empty-block-parent'空塊的 CSS 類(視覺化構建器)
containerPropsRecord<string, any>{}繫結到容器的其他屬性
showEmptyStatebooleantrue當沒有塊時顯示空狀態
emptyStateClassstring'contentstack-empty-state'空狀態的 CSS 類
emptyStateMessagestring'沒有內容塊可用'空狀態中顯示的訊息

高階屬性

屬性型別預設描述
keyFieldstring'_metadata.uid'塊的自定義鍵欄位
autoExtractBlockNamebooleantrue從物件鍵中自動提取塊名稱
blockNamePrefixstring''要從塊名稱中刪除的字首

SEO 元資料支援(新功能)

該元件在使用自動獲取模式時可以自動設定 SEO 元資料,使用 Nuxt 的原生 useSeoMeta 型別和功能。

簡單用法

<template>
  <!-- Pass SEO metadata directly using useSeoMeta format -->
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    :seo-meta="{
      title: 'My Page Title',
      description: 'My page description',
      ogTitle: 'My Social Title',
      ogDescription: 'My social description',
      ogImage: 'https://example.com/image.jpg',
      twitterCard: 'summary_large_image',
    }"
    :component-map="componentMapping"
  />
</template>

來自條目資料的動態 SEO

<script setup>
// Get entry data first, then use it for SEO
const { data: page } = await useGetEntryByUrl({
  contentTypeUid: "page",
  url: useRoute().path,
});

// Create SEO object from entry data
const seoMeta = computed(() => ({
  title: page.value?.seo_title || page.value?.title,
  description: page.value?.seo_description || page.value?.description,
  ogTitle: page.value?.social_title || page.value?.title,
  ogDescription: page.value?.social_description || page.value?.description,
  ogImage: page.value?.featured_image?.url,
  canonical: `https://example.com${page.value?.url}`,
  robots: page.value?.no_index ? "noindex,nofollow" : "index,follow",
}));
</script>

<template>
  <!-- Use computed SEO metadata -->
  <ContentstackModularBlocks
    :blocks="page?.components"
    :seo-meta="seoMeta"
    :component-map="componentMapping"
  />
</template>

從條目資料自動生成 SEO

當使用自動獲取模式時,您可以從獲取的條目資料中自動生成 SEO 元資料

<template>
  <!-- Auto-generate SEO using default field mapping -->
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    :auto-seo-meta="true"
    :component-map="componentMapping"
  />
</template>

自定義欄位對映

<template>
  <!-- Custom field mapping for SEO generation -->
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    :auto-seo-meta="{
      title: 'page_title|title',
      description: 'meta_description|description',
      ogTitle: 'social_title|page_title|title',
      ogImage: 'featured_image.url',
      canonical: 'canonical_url',
      twitterCard: 'summary_large_image',
    }"
    :component-map="componentMapping"
  />
</template>

預設自動 SEO 欄位對映

autoSeoMeta: true 時,這些欄位會自動對映

SEO 元標籤條目欄位(回退順序)
titleseo_titletitlename
描述seo_descriptiondescriptionsummary
ogTitleseo_titletitlename
ogDescriptionseo_descriptiondescriptionsummary
ogImagefeatured_image.urlog_image.urlimage.url

結合手動和自動 SEO

<template>
  <!-- Auto-generate base SEO, override specific fields -->
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    :auto-seo-meta="true"
    :seo-meta="{
      canonical: 'https://example.com' + $route.path,
      robots: 'index,follow',
    }"
    :component-map="componentMapping"
  />
</template>

支援所有 useSeoMeta 選項

由於我們將 seoMeta prop 直接傳遞給 Nuxt 的 useSeoMeta,因此您可以使用 100 多個受支援的元標籤中的任何一個

優點

  • XSS 安全:使用 Nuxt 內建的 useSeoMeta 進行安全的元標籤處理
  • TypeScript 支援:具有 100 多種元標籤型別的完整型別安全
  • 自動生成:自動從獲取的條目資料中提取 SEO
  • 靈活對映:支援回退的自定義欄位對映
  • 優先順序系統:手動 seoMeta 覆蓋自動生成的值
  • SSR 優先:SEO 元資料在伺服器端渲染期間設定,以實現最佳 SEO
  • 搜尋引擎就緒:爬蟲訪問您的頁面時可用的元標籤
  • 靈活:可選擇自動檢測、自定義對映或基於函式邏輯

資料結構支援

該元件支援兩種常見的 Contentstack 模組塊結構

自動提取(預設)

{
  "components": [
    {
      "hero": {
        "title": "Welcome",
        "subtitle": "To our site"
      },
      "_metadata": { "uid": "hero_123" }
    },
    {
      "grid": {
        "columns": 3,
        "items": [...]
      },
      "_metadata": { "uid": "grid_456" }
    }
  ]
}

基於內容型別

{
  "modular_blocks": [
    {
      "_content_type_uid": "hero_block",
      "title": "Welcome",
      "subtitle": "To our site",
      "_metadata": { "uid": "hero_123" }
    },
    {
      "_content_type_uid": "grid_block",
      "columns": 3,
      "items": [...],
      "_metadata": { "uid": "grid_456" }
    }
  ]
}

元件屬性

每個渲染的元件都會接收

// Original block props
{
  title: "Welcome",
  subtitle: "To our site",
  // ... other block fields

  // Additional meta props
  blockType: "hero",
  blockMetadata: { uid: "hero_123", ... }
}

即時預覽整合

元件自動新增即時預覽屬性

<section class="contentstack-modular-blocks">
  <component
    :is="Hero"
    :title="Welcome"
    data-block-type="hero"
    data-block-index="0"
    data-cslp="hero.title"
  />
</section>

插槽

該元件提供了幾個插槽,用於自定義不同狀態

插槽描述可用時機
loading自定義載入狀態內容自動獲取已啟用且資料正在載入
error自定義錯誤狀態內容自動獲取失敗或遇到錯誤
empty自定義空狀態內容沒有可用塊可渲染
<template>
  <ContentstackModularBlocks
    content-type-uid="page"
    :url="$route.path"
    :component-map="componentMapping"
  >
    <!-- Custom loading spinner -->
    <template #loading>
      <div class="flex items-center justify-center py-12">
        <div
          class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"
        ></div>
        <span class="ml-3">Loading page content...</span>
      </div>
    </template>

    <!-- Custom error message -->
    <template #error>
      <div class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
        <h3 class="text-red-800 font-semibold">Content Unavailable</h3>
        <p class="text-red-600 mt-2">
          Unable to load page content. Please try again later.
        </p>
      </div>
    </template>

    <!-- Custom empty state -->
    <template #empty>
      <div class="text-center py-12 text-gray-500">
        <h3 class="text-lg font-medium">No Content Available</h3>
        <p class="mt-2">This page doesn't have any content blocks yet.</p>
      </div>
    </template>
  </ContentstackModularBlocks>
</template>

錯誤處理

  • 缺失元件:回退到 fallbackComponent
  • 空塊:顯示可配置的空狀態(可透過 #empty 插槽自定義)
  • 無效資料:優雅地處理格式錯誤的塊資料
  • 缺失鍵:使用基於索引的鍵作為回退
  • 自動獲取錯誤:顯示錯誤狀態(可透過 #error 插槽自定義)
  • 載入狀態:在自動獲取期間顯示載入狀態(可透過 #loading 插槽自定義)

ContentstackFallbackBlock

該模組包含一個內建的回退元件,為未對映的塊型別提供了開發者友好的顯示。該元件自動:

  • 顯示塊標題(來自 titlenameheadingblockType 欄位)
  • 在樣式徽章中顯示塊型別
  • 在可展開的詳細資訊部分將所有屬性渲染為格式化的 JSON
  • 提供有關如何正確對映元件的有用指導
  • 支援暗模式以提供更好的開發者體驗

功能

  • 🎨 風格化介面,具有清晰的視覺層次結構
  • 📱 響應式設計,適用於所有螢幕尺寸
  • 🌙 暗模式支援,透過 prefers-color-scheme
  • 🔍 可摺疊 JSON,避免 UI 混亂
  • 🛠️ 開發者提示,顯示如何修復未對映的元件

示例輸出

┌─────────────────────────────────────┐
│ Welcome Hero                Type: hero │
├─────────────────────────────────────┤
│ ▶ View Props                        │
│   {                                 │
│     "title": "Welcome Hero",        │
│     "subtitle": "Get started now",  │
│     "cta_text": "Learn More"       │
│   }                                 │
├─────────────────────────────────────┤
│ This is a fallback component.       │
│ Map "hero" to a proper Vue component│
└─────────────────────────────────────┘

您可以透過提供自己的 fallbackComponent 來覆蓋此設定

<ContentstackModularBlocks
  :blocks="page.components"
  :component-map="componentMapping"
  :fallback-component="MyCustomFallback"
/>

可組合項

此模組提供了幾個可組合項,用於處理 Contentstack 內容。所有可組合項都支援即時預覽、個性化並使用 Nuxt 的快取系統。

useGetEntryByUrl

使用 URL 欄位查詢任何條目。監聽即時編輯更改並支援個性化。

const { data: page } = await useGetEntryByUrl<Page>({
  contentTypeUid: "page",
  url: "/about",
  referenceFieldPath: ["reference.fields"],
  jsonRtePath: ["rich_text_field"],
  locale: "en-us",
  replaceHtmlCslp: true,
});

useGetEntry

透過其 UID 獲取單個條目。

const { data: article } = await useGetEntry<Article>({
  contentTypeUid: "article",
  entryUid: "your_entry_uid",
  referenceFieldPath: ["author", "category"],
  jsonRtePath: ["content"],
  locale: "en-us",
});

useGetEntries

透過篩選、分頁和排序獲取多個條目。

const { data: articles } = await useGetEntries<Article>({
  contentTypeUid: "article",
  referenceFieldPath: ["author"],
  locale: "en-us",
  limit: 10,
  skip: 0,
  orderBy: "created_at",
  includeCount: true,
  where: {
    status: "published",
    published_at: { $gte: "2024-01-01" },
    tags: { $exists: true },
  },
});

// Access results
console.log(articles.value?.entries); // Article[]
console.log(articles.value?.count); // Total count if includeCount: true

useGetAsset

透過其 UID 獲取單個資產。

const { data: image } = await useGetAsset<Asset>({
  assetUid: "your_asset_uid",
  locale: "en-us",
});

useGetAssets

透過篩選和分頁獲取多個資產。

const { data: images } = await useGetAssets<Asset>({
  locale: "en-us",
  limit: 20,
  orderBy: "created_at",
  where: {
    content_type: "image/jpeg",
    // Note: Asset filtering is limited; most filters are applied client-side
  },
});

查詢運算子

條目可組合項(useGetEntriesuseGetEntryuseGetEntryByUrl)在 where 引數中支援高階查詢運算子

注意:資產篩選的伺服器端支援有限。useGetAssets 可組合項在獲取後將大多數篩選器應用於客戶端。

where: {
  // Exact match
  status: "published",

  // Array contains
  tags: ["tech", "news"],

  // Comparison operators
  view_count: { $gt: 1000 },
  created_at: { $gte: "2024-01-01", $lt: "2024-12-31" },

  // Existence checks
  featured_image: { $exists: true },

  // Pattern matching
  title: { $regex: "nuxt.*contentstack" },

  // Not equal
  author: { $ne: "guest" }
}

@nuxt/image 整合

此模組包含一個自定義的 @nuxt/image 提供程式,用於與 Contentstack 的影像交付 API 無縫整合。

設定

  1. 安裝 @nuxt/image
npm install @nuxt/image
  1. 將這兩個模組新增到您的 nuxt.config.ts
export default defineNuxtConfig({
  modules: ["nuxt-contentstack", "@nuxt/image"],

  // Configure @nuxt/image to use Contentstack provider
  image: {
    providers: {
      contentstack: {
        name: "contentstack",
        provider:
          "node_modules/nuxt-contentstack/dist/runtime/providers/contentstack",
        options: {},
      },
    },
    // Optional: Set Contentstack as default provider
    provider: "contentstack",
  },
});

使用

配置完成後,您可以直接使用 Contentstack 資產 URL 的 <NuxtImg><NuxtPicture> 元件 - 無需將資產 UID 或版本 UID 作為修飾符傳遞

<template>
  <!-- Basic usage with Contentstack assets -->
  <NuxtImg
    :src="page.image.url"
    :alt="page.image.title"
    width="800"
    height="400"
    :modifiers="{
      auto: 'webp,compress',
      quality: 90,
    }"
    provider="contentstack"
  />

  <!-- Responsive image with automatic optimization -->
  <NuxtImg
    :src="hero.image.url"
    :alt="hero.image.title"
    sizes="100vw sm:50vw lg:33vw"
    densities="1x 2x"
    :modifiers="{
      auto: 'webp,compress',
      quality: 90,
    }"
    provider="contentstack"
  />

  <!-- Advanced transformations -->
  <NuxtImg
    :src="gallery.image.url"
    width="600"
    height="400"
    fit="cover"
    :modifiers="{
      blur: 5,
      brightness: 110,
      contrast: 120,
      saturation: 130,
    }"
    provider="contentstack"
  />

  <!-- Art direction for different devices -->
  <NuxtPicture
    :src="article.featured_image.url"
    :imgAttrs="{ alt: article.title }"
    sizes="100vw md:50vw"
    :modifiers="{
      auto: 'webp,compress',
      quality: 85,
    }"
    provider="contentstack"
  />
</template>

優點

  • 自動影像最佳化,支援 WebP 和壓縮
  • 響應式影像,支援尺寸和密度
  • Contentstack 轉換,透過影像交付 API
  • 懶載入和效能最佳化
  • 藝術方向支援,透過 NuxtPicture
  • 開發者體驗 - 熟悉的 @nuxt/image API

可用修飾符

Contentstack 提供程式支援所有標準 @nuxt/image 修飾符以及 Contentstack 特定的轉換

// Common modifiers
:modifiers="{
  // Image optimization
  auto: 'webp,compress',
  quality: 90,

  // Dimensions and cropping
  width: 800,
  height: 400,
  fit: 'cover', // crop, bounds, fill, scale

  // Effects
  blur: 5,
  brightness: 110,
  contrast: 120,
  saturation: 130,

  // Format
  format: 'webp',
}"

useImageTransform 可組合項

對於需要對影像轉換進行程式設計控制的高階用例,您可以使用 useImageTransform 可組合項。當您需要動態應用轉換或使用常規 <img> 標籤而不是 <NuxtImg> 時,這尤其有用。

const { transformedUrl, updateTransform, resetTransform } = useImageTransform(
  originalImageUrl,
  {
    width: 800,
    height: 600,
    quality: 80,
    format: "webp",
    fit: "crop"
  }
);

// Use in template
<img :src="transformedUrl" alt="Transformed image" />

// Update transforms reactively
updateTransform({ width: 1200, quality: 90 });

// Advanced transforms
const { transformedUrl: advancedUrl } = useImageTransform(imageUrl, {
  width: 800,
  height: 600,
  quality: 85,
  format: "webp",
  overlay: {
    relativeURL: "/watermark.png",
    align: "bottom-right",
    width: "20p" // 20% of base image
  },
  sharpen: {
    amount: 5,
    radius: 2,
    threshold: 0
  },
  saturation: 10,
  brightness: 5
});

何時使用 useImageTransform<NuxtImg>

  • 在大多數情況下使用 <NuxtImg> - 它經過最佳化,支援響應式影像,並處理懶載入
  • 當您需要動態轉換、使用常規 <img> 標籤或構建自定義影像元件時,使用 useImageTransform

支援的影像轉換

  • 尺寸widthheightdpr(裝置畫素比)
  • 質量和格式qualityformatauto 最佳化
  • 裁剪fitcroptrim
  • 效果blursaturationbrightnesscontrastsharpen
  • 疊加:新增水印或其他影像
  • 高階orientpadbg-colorframeresizeFilter

貢獻

本地開發
# Install dependencies
npm install

# Generate type stubs
npm run dev:prepare

# Develop with the playground
npm run dev

# Build the playground
npm run dev:build

# Run ESLint
npm run lint

# Run Vitest
npm run test
npm run test:watch

# Release new version
npm run release