Utilizing PrimeVue for Seamless Theme-Change Functionality

Is there a way to change the theme using Prime Vue without directly modifying the index.html file with

<link id="lara-light-indigo" rel="stylesheet" href="/themes/lara-light-indigo/theme.css">
?

Currently, I am managing my theme by importing it in the main.js file like this:

import "primevue/resources/themes/lara-light-indigo/theme.css";
. Now, I want to utilize this method to switch themes on the Topbar.vue page.

import { usePrimeVue } from 'primevue/config';

const PrimeVue = usePrimeVue();
let currentTheme = ref(null);
if (localStorage.getItem('theme') != null) {
    currentTheme.value = localStorage.getItem('theme');
    toggleThemeDark();
} else {
    localStorage.setItem('theme', 'lara-light-indigo');
    currentTheme.value = 'lara-light-indigo';
    toggleThemeDark();
}
function toggleTheme() {
    
    const newTheme = localStorage.getItem('theme') === 'lara-light-indigo' ? 'lara-dark-indigo' : 'lara-light-indigo';
  PrimeVue.changeTheme(localStorage.getItem('theme'), newTheme, 'lara-light-indigo', () => {
    currentTheme = newTheme;
    document.querySelector('.moon').classList.toggle('sun');
   
  });   
  localStorage.setItem('theme', newTheme);

};

function toggleThemeDark() {
    if(currentTheme.value == 'lara-dark-indigo'){
        PrimeVue.changeTheme('lara-light-indigo', 'lara-dark-indigo', 'lara-light-indigo', () => {
    document.querySelector('.moon');
   
  }); 
    }else{
        PrimeVue.changeTheme('lara-dark-indigo', 'lara-light-indigo', 'lara-light-indigo', () => {
            document.querySelector('.dark');
    document.querySelector('.moon').classList.toggle('sun');
   
  }); 
    }
};
<div class="dark" @click="toggleTheme">
        <div class="tdnn" :class="{ 'day': currentTheme === 'lara-light-indigo' }">
            <div class="moon" :class="{ 'moon': currentTheme === 'lara-dark-indigo' }"></div>
        </div>
    </div>

Previously, when I used the link tag in the index.html file, everything worked well. However, I now need to find an alternative solution that does not involve modifying the index.html directly due to recent updates in Prime Vue or similar reasons.

Answer №1

Modify the theme dynamically without altering the index.html file.

import { usePrimeVue } from 'primevue/config';
import { ref } from 'vue';

export default {
  setup() {
    const PrimeVue = usePrimeVue();
    const currentTheme = ref(null);

    if (localStorage.getItem('theme') != null) {
      currentTheme.value = localStorage.getItem('theme');
      toggleThemeDark();
    } else {
      localStorage.setItem('theme', 'lara-light-indigo');
      currentTheme.value = 'lara-light-indigo';
      toggleThemeDark();
    }

    function toggleTheme() {
      const newTheme =
        localStorage.getItem('theme') === 'lara-light-indigo'
          ? 'lara-dark-indigo'
          : 'lara-light-indigo';

      PrimeVue.changeTheme(
        localStorage.getItem('theme'),
        newTheme,
        'lara-light-indigo',
        () => {
          currentTheme.value = newTheme;
          document.querySelector('.moon').classList.toggle('sun');
        }
      );

      localStorage.setItem('theme', newTheme);
    }

    function toggleThemeDark() {
      if (currentTheme.value === 'lara-dark-indigo') {
        PrimeVue.changeTheme(
          'lara-light-indigo',
          'lara-dark-indigo',
          'lara-light-indigo',
          () => {
            document.querySelector('.moon');
          }
        );
      } else {
        PrimeVue.changeTheme(
          'lara-dark-indigo',
          'lara-light-indigo',
          'lara-light-indigo',
          () => {
            document.querySelector('.dark');
            document.querySelector('.moon').classList.toggle('sun');
          }
        );
      }
    }

    return {
      currentTheme,
      toggleTheme,
    };
  },
};

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

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

`an error occurs when trying to loop through an object and add a key``

I'm currently facing an issue with adding a key to an object through looping. Here is the code snippet: function checkResult(want, reference) { const keys = Object.keys(reference); for(let i=0; i<Object.keys(reference).length; i++){ console ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

React client side componentDidMount function encountering issues (server side rendering)

Greetings to the Stackoverflow community Apologies in advance if my explanation is not clear enough When a user directly types a URL, the server makes a request, fetches the corresponding data, and renders it on the screen flawlessly. However, when a us ...

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

Tips for simultaneously submitting two forms or merging them into a single form

Trying to merge two different forms into one has proven to be quite challenging for me. The recommendation I received was to move the create method from ChargesController to OrderController, but it's not as simple as that. The Charges Form requires j ...

Store the decoded user information in the database for safekeeping

I have developed an application where users can capture images and send them to the database with ease. Upon logging in, each user receives a token. As long as the token is valid, they do not need to log in again. To implement JWT authentication, I refer ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

Modifying Arrays with Different Data Structures in JavaScript

I am interested in implementing the following scenario: var A = ["Jon","Brad","Rachel"]; var B = ["Male","Male","Female"]; var C = [ {"Jon","Male"}, {"Brad","Male"}, {"Rachel","Female"} ] Can you guide me on how to retrieve var C using javascrip ...

What is the best way to have an HTML radio button automatically display as selected upon loading if the stored value is "on"?

Utilizing Javascript alongside html: I am facing an issue where a list containing radio buttons is dynamically loaded based on stored data when the page launches. Despite the stored value of the radio being set to "on", the radio button does not show up a ...

Is it possible to use Javascript to query the neo4j database?

After creating a geohash neo4j database for NYC Taxi data, the next step is to visualize it on a map. I decided to use Leaflet as a JavaScript library. Using static data, I was able to plot geohash data in Leaflet: https://i.sstatic.net/AtQKZ.jpg Now, my ...

curved edges and accentuate the chosen one

I've been working on an angularJS application that includes a webpage with multiple tabs created using angularJS. Check out this example of the working tabs: http://plnkr.co/edit/jHsdUtw6IttYQ24A7SG1?p=preview My goal is to display all the tabs with ...

Exploring the interactive features of discord.js version 12

Currently, I have a bot set up to log when invites are created, but the logs are only going to a specific channel ID that I designated. I would like to make it so that this can be changed on a per-server basis. Intended Output User: !log channel (CHANNEL ...

How to prompt a nested function to refresh in Angular by using a force

As a newcomer to Angular(1.x), I am currently integrating it into the app I am working on. The app fetches user data via ajax, which includes multiple nested arrays, and then displays them using nested ng-repeat directives. Within the innermost repeat, I h ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

Creating a Welcome Page for my React Application with IndexRoute

I am in the process of setting up a landing page that will then redirect to my main home page using React. I have created a component for the landing page named Splash. I am attempting to utilize IndexRoute to make sure my app initially displays Splash as ...