Sworld

Sworld

The only way to do great work is to love what you do.

Nuxt.js 內容使用專案組件報錯

問題描述#

最近使用 Nuxt.js 的 Content 模塊時,發現其支持項目中寫好的 Vue 組件,相關文檔可以參考 這裡
我在頁面中嘗試添加如下組件,該組件位於~/components/XXX/VideoArea.vue

<script setup lang="ts">
import ArtPlayer from "artplayer"

const art_ref = ref<HTMLInputElement | null>(null)
const art_instance = ref<Artplayer | null>(null);

const props = defineProps<{ url: string }>()

onMounted(() => {
    if (!art_ref.value) return
    // 文檔參考: https://artplayer.org/document/start/option.html
    art_instance.value = new ArtPlayer({
        // 指定播放器的容器元素
        container: art_ref.value,
        // 設置視頻的 URL
        url: props.url,
        // 啟用自動迷你模式
        autoMini: true,
        // 啟用自動調整大小
        autoSize: true,
        // 啟用全屏模式
        fullscreen: true,
        // 使用服務器端渲染
        // useSSR: true,
        // 啟用快進功能
        fastForward: true,
        // 鎖定播放器界面
        lock: true
    })
})
</script>

<template>
    <div ref="art_ref" class="h-96 mr-auto">
        <slot></slot>
    </div>
</template>

對應 Content

---
title: '標題'
description: '簡述'
---
::xxx-video-area{url="視頻鏈接"}
視頻描述
::

發現啟動後報錯 If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.,後來發現可能是沒有設定全局組件,文檔中有提到:

Components that are used in Markdown has to be marked as global in your Nuxt app if you don't use the components/content/ directory, visit Nuxt 3 docs to learn more about it.
如果在 Nuxt 應用中使用的組件未放置在 components/content/ 目錄下,則需將其標記為全局組件。

對比一下,我的組件在~/components/XXX/下,而不是在~/components/content/下,因此無法訪問到該組件。

解決方案#

方案一:將組件移動到~/components/content/目錄下#

假設你的組件僅用於內容頁面,可以將其移動到~/components/content/目錄下,這樣 Nuxt Content 模塊會自動識別並加載這些組件。

方案二:將組件名稱改為VideoArea.global.vue#

參考官方文檔,我們修改文件後綴名也可以達到全局化的效果

方案三:將所有組件默認設為全局#

nuxt.config.ts中,我們需要增加組件選項,設為全局即可

export default defineNuxtConfig({
  compatibilityDate: '2024-04-03',
  devtools: { enabled: true },
  css: ['~/assets/css/main.css'],

  postcss: {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  },

  modules: ['@nuxt/content'],

  // 為了適配 Nuxt content 必須全局註冊
  // 注意下面這塊,上面的如果你和我不同不需要改動
  components: {
    global: true,
    dirs: ['~/components']
  },
})
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。