[Vuejs]-Create vue mixin for theme switcher vuejs

1πŸ‘

βœ…

I see several problems in your mixin.

Local Storage.

Be sure that you are saving theme-color else you will get an error if is not in the local storage.

methods: {
    toggleTheme() {
      const storedTheme = localStorage.getItem("theme-colour");
      if (!storedTheme) {
        localStorage.setItem("theme-colour", "theme-light");
        this.currentTheme = "theme-dark";
      }
      if (storedTheme === "theme-light") {
        localStorage.setItem("theme-colour", "theme-light");
        this.currentTheme = "theme-dark";
      } else {
        localStorage.setItem("theme-colour", "theme-dark");
        this.currentTheme = "theme-light";
      }
    },
  },

Structure of the mixin

Am not sure if you are importing the mixin correctly or not so am going to add this here just in case. This is the way i make and import mixin, following the docs of course. If you are using the vue cli, the mixin should be on its own file, this way follows that idea.

mixin.js

export default {
  data() {},
  methods {}
}

AnyVueComponent.vue

<template>
...
</template>
<script>
  import mixin from 'path to my mixin';
  export default {
    ......
    mixins: [mixin]
    ......
  }
</script>

currentTheme variable reactivity

You don’t have to keep loading from the localStorage you can save all the times but load just on mounted, kind of like this:

mixin.js

export default {
  data() {
    currentTheme: ''
  },
  mounted(){
    const storedTheme = localStorage.getItem("theme-colour");
    if (!storedTheme) {
      this.currentTheme = "theme-light"
    }else{
      this.currentTheme = localStorage.getItem("theme-colour");
    }
  },
  methods {...}
}

Using this way for class binding.

//Any format you want to do to currentTheme do it inside the computed
:class=[currentTheme]

Check this sandbox:

https://codesandbox.io/s/exciting-keller-nowok?file=/src/App.vue

πŸ‘€jogarcia

Leave a comment