I am working on implementing a theme changer using Vue3 and Tailwind CSS. One major issue I am encountering is with the emit event and displaying the currently selected button. Although I believe I have set up the emit event correctly (as shown in the code above), I am struggling to show the active state of the current color theme once it has been clicked. Interestingly, if I place the code outside of a component, everything works as expected.
Here is the code for the theme changer:
<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', colors[themeColor])"
>
<svg v-if="!index" 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
})
defineEmits(['color'])
</script>
And here is how you can implement this code:
<template>
<ThemeChanger :theme-colors="themeColors" @colors="c => 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 color = ref(colors[themeColors[0]])
</script>