Having trouble with triggering events and getting the icon to highlight on the current button in Vue3

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>

Answer №1

It appears that you have a mismatch in the event names within your code. You are emitting an event called color at

@click="$emit('color', colors[themeColor])"
,

while listening to an event called colors at

<ThemeChanger :theme-colors="themeColors" @colors="c => color = c" />

To resolve this issue, it is recommended to update the event names so they align correctly for the functionality to work as intended.

In order to display the check mark based on the current theme, one approach could be to introduce a new prop such as currentThemeColor in the ThemeChanger component.

Within your v-for loop, you can implement something like the following:

<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="currentThemeColor === themeColor" ... >
</div>

This method allows the ThemeChanger component to refresh whenever the prop changes, ensuring the desired behavior. While using refs is another option, transitioning the theme logic to a global provider in the future may necessitate minimal adjustments with the current setup utilizing props.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Securing access with Vue.js authentication even if the URL is entered manually

Within my main.js file, I have configured my routes array to include: meta : { requiresAuth: true } for all components except the UserLogin page. For navigation resolution, I have implemented a check before each route: router.beforeEach((to, from, next ...

Tips for ensuring your webpage stays current with regular updates through JavaScript

This webpage acts as a dynamic newsboard, constantly updated with the latest data from my Database through an API, all without requiring a page refresh. While the timer solution seemed simple, I am seeking a more resource-efficient approach. I have resear ...

Error: The session ID is not currently active

I encountered a problem with my tests failing when running them on TFS, showing the following error: WebDriverError: No active session with ID Failed: No active session with ID Interestingly, these same tests are passing locally. Everything was working ...

Ensuring the corner link remains at the top when expanding or in mobile mode with mdBootstrap's navbar

I have implemented Material Design Bootstrap on my responsive website. When viewing the website on a large screen, the navbar at the top displays: A link to my brand aligned to the left Two page links A profile dropdown aligned to the right Large scree ...

Javascript function that triggers at the end of a time update

How can I ensure that the alert event is triggered only once at the 15-second mark of a 45-second video? The code snippet below initiates the alert, but how can I modify it to make sure the alert only appears once. var video = document.getElementById("m ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...

Divide and conquer Excel data with JavaScript based on a specific key

My current task involves extracting data from Excel using JavaScript. The extracted output is structured as follows: { "Responsible": "Grey", "Goal": 0.823, "Jan": 0.8621397507374327, "Feb&q ...

Reinvent the AJAX functionality

Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

The app.html for the skygear/react-chat-demo is malfunctioning

I followed the instructions provided in the Skygear manual at https://docs.skygear.io/guides/advanced/server/ The skygear-server-darwin-amd64 started successfully. Then, I attempted to run the react-chat-demo project from https://github.com/skygear-de ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

Tips for showcasing an HTML Element from a different website

Suppose I have the identifier of a class, is there a way to extract the HTML content associated with that class and convert it into a string? I am not necessarily looking for specific code, but any helpful resources would be greatly appreciated. I am unsu ...

What is the best way to include and delete several images on a canvas?

Recently, I've started working with canvas in HTML5 and I'm tasked with creating a paint application. One of the features I need to implement is the ability to dynamically add selected images to the canvas as the mouse moves, and then have the fu ...

What is the process for indicating the cache directory in npm5 when using the install command?

When using yarn, you can specify the cache folder with yarn --cache-folder [CACHE_FOLDER]. Is there an npm5 alternative to this? One option is to set the cache folder with a separate command: npm config set cache [CACHE_FOLDER]. However, I'm wonderin ...

How can I utilize a service for monitoring user data and ensuring that $watch() functions properly?

I'm a beginner when it comes to AngularJS and currently working on building a website that has a navigation bar dependent on the user's login status. My approach involves using a state model design with the Nav controller as the parent state for ...

Vue: Ensure user-triggered changes are detected in form input

Hello everyone, I recently started using Vue and I'm trying to achieve the following goal. I have a form with some data and a save button. Before the page fully loads, it needs to fetch data from the database and pre-fill the form. The save button sh ...

Begin by generating lines and text that originate from the center of spherical objects in ThreeJS

Currently, I am constructing a solar system simulation using ThreeJS. As part of the functionality, when I select a planet's name, the camera zooms in on that specific planet. My goal now is to create a visual element that consists of a 2D line origin ...

Updating the jQuery mobile webpage

I have set up a small demo with two pages - the Home page and the Team 1 page. By clicking on the navigation menu, you can navigate to the Team 1 page from the Home page. However, if you are already on the Team 1 page and click on the Team 1 button again ...

"Troubleshooting Image Loading Issues in Next.js: A Guide to Reloading Unresponsive

https://i.sstatic.net/FLdrA.jpgHello, I am facing an issue with rendering 300 images from IPFS data. Occasionally, around 3-4 of the images fail to load and result in a 404 error. Even after refreshing the page, these unloaded images remain inaccessible. I ...

Utilize Material UI's TouchRipple Component to enhance the interactivity of custom elements and components

Within my material-ui application, I have a curated list featuring columns and icon buttons. Upon selecting an item from the list, I desire to incorporate the ripple effect characteristic of Material Design. Although Material UI provides lists with built ...