2021-04-29

Switch Vue3 (PrimeVue) theme on load and click

Recommend way of including themes is by import in main.js file at root of the app:

import 'primevue/resources/themes/arya-orange/theme.css';

But I'm look for a way to switch CSS file based on user system theme and on user selection so i moved this in my main App.vue:

export default {
  name: "App",
  components: {
    HelloWorld,
    toDo,
  },
  mounted() {

    //window.matchMedia('(prefers-color-scheme: dark)').matches ? do dark : do light
  },
};

<style>
@media (prefers-color-scheme: dark) {
  @import url("assets/themes/arya-orange/theme.css");
}
@media (prefers-color-scheme: light) {
  @import url("assets/themes/arya-orange/theme.css");
}
</style>

I can not import anything inside mounted and in styles tag I can not import inside media also, both are not correct way of usage.

I can not find any other way online or guidance to solve this. All solutions are based on scoping components, using classes etc.

I could wrap all rules in one theme to

@media (prefers-color-scheme: dark) {

and another for light. But then again how could I switch on user selection?

Please advise.

EDIT:

I figured it out how can I do it on load:

(async () => {
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    await import('primevue/resources/themes/arya-orange/theme.css');
  }else {
    await import('primevue/resources/themes/saga-blue/theme.css');
  }
})();

If someone can advise how to do it on click.



from Recent Questions - Stack Overflow https://ift.tt/3xHXWBY
https://ift.tt/eA8V8J

1 comment:

  1. I haven't tried this yet, but instead of doing it on click I would think the "click" saves a setting in a cookie/local storage then forces a refresh. Then on the refresh, you use your code as-is except in the if statement look for the cookie instead of the media query.

    ReplyDelete