You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tailwind.config.js中利用Nuxt 3 Cookie实现动态主题色?

动态切换Nuxt应用主色调的问题

我希望实现一个用户可更新的变量,以此改变应用的主色调。但无法让tailwind.config.js文件与Nuxt应用通信,使其知晓应设置的主色。我尝试使用不同的Cookie库来实现这一功能,包括Nuxt内置的useCookie、VueUse的useCookies以及universal-cookies,但每次tailwind.config.js中Cookie值都显示为undefined,而浏览器中能显示正确的值。

app.vue 代码

<template>
  <div>
    <div class="bg-red-600 h-16 mb-4">HELLO WORLD</div>
    <div class="bg-primary-600 h-16 mb-4">HELLO WORLD</div>
    <button class="bg-blue-200 rounded-lg p-4 mx-2" @click="myColor = 'blue'">
      Blue
    </button>
    <button class="bg-green-200 rounded-lg p-4" @click="myColor = 'green'">
      Green
    </button>
    <body class="mx-2">
      My color is: {{ myColor }}
    </body>
  </div>
</template>

<script setup>
const myColor = useCookie('myColor', {
  default: () => 'orange',
  watch: true,
});
</script>

tailwind.config.js 代码

/** @type {import('tailwindcss').Config} */
const colors = require('tailwindcss/colors');
// need to figure out how to make this dynamic
const color = 'blue';

exports.darkMode = 'class';
exports.content = [
  './components/**/*.{js,vue,ts}',
  './layouts/**/*.vue',
  './pages/**/*.vue',
  './plugins/**/*.{js,ts}',
  './nuxt.config.{js,ts}',
  './app.vue',
];

if (color === 'blue') {
  exports.theme = {
    extend: {
      colors: {
        primary: colors.blue,
      },
    },
  };
}
if (color === 'green') {
  exports.theme = {
    extend: {
      colors: {
        primary: colors.green,
      },
    },
  };
}
if (color === 'orange') {
  exports.theme = {
    extend: {
      colors: {
        primary: colors.orange,
      },
    },
  };
}

内容的提问来源于stack exchange,提问作者Taylor Finklea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:25:34