使用 Nuxt Color Mode 套件取得主題(Theme)名稱(以 DaisyUI 為例)

在網路上看到許多問題,都是想要取得 DaisyUI 當前的主題名稱,筆者最近也遇到相同的需求,原因是因為想要透過當前主題名稱來變更其他第三方套件的主題。而目前比較多的回答都是取得指定的顏色色碼,無法取得主題名稱,直到發現了這個 Nuxt3 的套件: Nuxt Color Mode

NuxtColorMode 要安裝很簡單,只有兩步驟:
    
npm install --save-dev @nuxtjs/color-mode
    

在 nuxt.config.ts 中增加
    
export default defineNuxtConfig({
  modules: ['@nuxtjs/color-mode']
})
    

接下來要讓 useColorMode 可以讀取主題還要再調整 nuxt.config.ts 的設定:
    
export default defineNuxtConfig({
    modules: [
        '@nuxtjs/tailwindcss',
        '@nuxtjs/color-mode',
    ],
    tailwindcss: {},
    colorMode: {
        preference: 'light', // 預設主題
        dataValue: 'theme', // html 標籤中的主題
    },
})
    

變更主題的範例程式碼: app.vue:
    
<template>
    <h1 class="p-8">主題: {{ $colorMode.value }}</h1>
    <div class="p-4 flex gap-8">
        <select class="select w-full max-w-xs" v-model="colorMode.preference">
            <option disabled selected>Theme</option>
            <option v-for="theme of themes" :key="theme">{{ theme }}</option>
        </select>
        <button class="btn">Button</button>
        <input type="range" min="0" max="100" value="40" class="range w-96"/>
    </div>
</template>


<script setup>
const colorMode = useColorMode()

console.log(colorMode.preference)

/**
 * daisyUI 主題清單
 * @type {string[]}
 */
const themes = [
    'light',
    'dark',
    'cupcake',
    'bumblebee',
    'emerald',
    'corporate',
    'synthwave',
    'retro',
    'cyberpunk',
    'valentine',
    'halloween',
    'garden',
    'forest',
    'aqua',
    'lofi',
    'pastel',
    'fantasy',
    'wireframe',
    'black',
    'luxury',
    'dracula',
    'cmyk',
    'autumn',
    'business',
    'acid',
    'lemonade',
    'night',
    'coffee',
    'winter',
];

</script>
    

在筆者測試時發現原本 DaisyUI 主題套用的方式是在 html 標籤上,但是是以不容易閱讀的類似亂碼的方式。現在終於會顯示為主題的名稱了:
    
<html class="drak-mode" data-theme="dark">
</html>
    



參考資料:
NuxtJs - Nuxt Tailwind
NuxtJs - Nuxt Color Mode

留言