DEV Community

suman kumar
suman kumar

Posted on

Switching Themes in a Vue.js Application with `<script setup>` and PrimeVue

In this post, we'll explore how to implement theme switching in a Vue.js application using the <script setup> syntax and PrimeVue. We'll create a simple Vue application where users can switch between different themes provided by PrimeVue.


Before we begin, make sure you have the following installed:

  • Vue.js
  • PrimeVue

Setting Up the Project

Let's start by setting up a new Vue.js project with PrimeVue. You can create a new Vue project using Vue CLI or integrate PrimeVue into an existing project.

Creating the Theme Switcher Component

We'll create a theme switcher component that allows users to select a theme from a dropdown menu. This component will use the <script setup> syntax, which is a more concise way to define Vue components.

    <!-- Theme Switcher -->
    <select v-model="selectedTheme" @change="changeTheme">
      <option value="vela">Vela</option>
      <option value="bootstrap">Bootstrap</option>
      <!-- Add other theme options as needed -->

<script setup>
import { ref } from 'vue';

const selectedTheme = ref('vela'); // Set the default theme here

const changeTheme = () => {
  // Dynamically change the theme by updating the href attribute
  const themeLink = document.querySelector('link[href*="/primevue/themes/"]');
  themeLink.href = `primevue/themes/${selectedTheme.value}/theme.css`;
Enter fullscreen mode Exit fullscreen mode

In this component, we define a <select> element to choose themes, and when the selection changes, it triggers the changeTheme function to dynamically update the theme by changing the href attribute of the theme stylesheet link.

Using the Theme Switcher Component

To use the theme switcher component, simply include it in your Vue application where you want the theme switching functionality.

    <ThemeSwitcher />

<script  setup>
import ThemeSwitcher from './ThemeSwitcher.vue';
Enter fullscreen mode Exit fullscreen mode


With this setup, you can easily implement theme switching in your Vue.js application using the <script setup> syntax and PrimeVue. Users can select their preferred theme from a dropdown menu, and the application's appearance will change dynamically.

Feel free to extend this example by adding more themes and customizing the theme-switching mechanism to fit your project's requirements.

That's it! You now have a Vue.js application with theme switching capabilities using <script setup> and PrimeVue. Happy coding!

Top comments (0)