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

Vue3+Tailwind主题切换器:Emit事件失效与按钮激活图标问题

Vue3 + Tailwind 主题切换问题修复

问题1:自定义emit事件未正常工作

错误原因

子组件通过defineEmits(['color'])定义的事件名为color,但父组件监听的是@colors,事件名称不匹配,导致触发事件后父组件无法接收回调。

修复方案

将父组件中的@colors改为@color,与子组件定义的事件名保持一致。

问题2:选中主题色按钮无法显示激活图标

错误原因

当前子组件中图标仅通过v-if="!index"固定显示在第一个按钮上,未与实际选中的主题关联,无法随选中状态动态切换。

修复方案

  1. 子组件新增currentTheme属性,接收父组件传入的当前选中主题名;
  2. 修改图标显示条件为判断当前按钮的主题是否与选中主题一致;
  3. 父组件维护当前选中的主题名,在emit回调中更新该值并传递给子组件。

修改后的完整代码

主题切换器组件(ThemeChanger.vue)

<template>
  <div class="flex space-x-1 bg-white rounded-full px-2 py-1">
    <button
      class="rounded-full"
      v-for="(themeColor, index) in themeColors"
      :key="`theme-changer-${index}`"
      :class="[index ? 'p-3' : 'p-1']"
      :style="{ backgroundColor: colors[themeColor][500] }"
      @click="$emit('color', themeColor, colors[themeColor])"
    >
      <svg v-if="themeColor === currentTheme" class="text-white w-4 h-4" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
        <path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 01.208 1.04l-9 13.5a.75.75 0 01-1.154.114l-6-6a.75.75 0 011.06-1.06l5.353 5.353 8.493-12.739a.75.75 0 011.04-.208z" clip-rule="evenodd" />
      </svg>
    </button>
  </div>
</template>

<script setup>
import colors from 'tailwindcss/colors'

defineProps({
  themeColors: Array,
  currentTheme: String
})

defineEmits(['color'])
</script>

组件引入代码

<template>
  <ThemeChanger :theme-colors="themeColors" :current-theme="currentTheme" @color="(theme, c) => { currentTheme = theme; color = c }" />
</template>

<script setup>
import { ref } from 'vue'
import ThemeChanger from '@/components/ThemeChanger.vue'
import colors from 'tailwindcss/colors'

const themeColors = [
  'indigo',
  'emerald',
  'blue',
  'yellow',
  'orange',
  'red',
]

const currentTheme = ref(themeColors[0])
const color = ref(colors[currentTheme.value])
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:47:27