vue.jsvuex

how to refresh the value of computed when it changes


I want to change the value of: class = "theme - $ {nightMode}" when I click toggle but it only works if I refresh the page and I can't figure out how to set up a watcher so that 'he looks at the value modify

<template>
  <div id="app" :class="`theme-${nightMode}`">
    <router-view />
    <Header />
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/molecules/Header/index.vue';
import Footer from '@/components/molecules/Footer/index.vue';

export default {
  name: 'App',

  components: { Header, Footer },
  data() {
    return {
      themeMode: ''
    };
  },

  computed: {
    nightMode() {
      const mode = localStorage.getItem('DarkMode');
      if (mode === 'true') {
        console.log('dark');
        return 'dark';
      } else {
        console.log('light');
        return 'light';
      }
    }
  },
  watch: {
    themeMode(newVal) {
      this.nightMode = newVal;
    }
  }
};
</script>

<style lang="scss" src="./assets/scss/style.scss"></style>

Solution

  • Below are the changes

           <template>
             <div id="app" :class="`theme-${themeMode}`">
               <router-view />
               <Header />
               <Footer />
             </div>
           </template>
           
           <script>
           import { mapGetters } from 'vuex'; // change Added
           import Header from '@/components/molecules/Header/index.vue';
           import Footer from '@/components/molecules/Footer/index.vue';
           
           export default {
             name: 'App',
           
             components: { Header, Footer },
             data() {
               return {
                 themeMode: 'light' // change Added
               };
             },
             computed: {
               ...mapGetters(['isDark']) // change Added
             },
             watch: { // change Added
               isDark(newVal) {
                this.themeMode = newVal ? 'dark' : 'light';
              }
             },
             mounted() {
               const mode = localStorage.getItem('DarkMode');
               if (mode === 'true') {
                   console.log('dark');
                   return 'dark';
                 } else {
                   console.log('light');
                   return 'light';
               }
             }
           };
           </script>
           
           <style lang="scss" src="./assets/scss/style.scss"></style>
           ```