【问题标题】:Reading from localstorage in nuxt js is not reactive从 nuxt js 中的 localstorage 读取不是反应式的
【发布时间】:2020-04-18 00:10:26
【问题描述】:

我正在尝试从 nuxt js 中的 locastorage 读取数据。

我使用了 process.browser if 语句。 没有错误。

这是我的代码:

  data() {
    return {
      classes: ['light', 'dark', 'darker'],
      current: 0
    }
  },
  created() {
    if (process.browser) this.getBgDarkness()

    console.log(this.classes[this.current])
  },
  methods: {
    makeBgDarker() {
      this.current < 2 ? (this.current += 1) : (this.current = 0)
      if (process.browser)
        window.localStorage.setItem('darknessLevel', this.current)
    },
    getBgDarkness() {
      this.current = Number(window.localStorage.getItem('darknessLevel'))
    }
  }

这是我的模板:

<header :class="['header position-relative', `header--${classes[current]}`]"></header>

localstorage 设置成功,我的current 数据同步到它。

但我的 css 类没有改​​变。

这是我的控制台: console screenshot

【问题讨论】:

    标签: vue.js vuejs2 local-storage nuxt.js


    【解决方案1】:

    嗯,在我看来它有效。尝试删除所有本地存储的东西,看看它是否有效。没有理由不...

    new Vue({
      el: "#app",
      data() {
        return {
          classes: ["light", "dark", "darker"],
          current: 0
        };
      },  
      methods: {
        makeBgDarker() {
          this.current === this.classes.length - 1
            ? (this.current = 0)
            : (this.current += 1);
        }
      }
    })
    .header--light {
      color: yellow;
    }
    .header--dark {
      color: blue;
    }
    .header--darker {
      color: darkblue;
    }
    <div id="app">
        <div :class="['header position-relative', `header--${classes[current]}`]">Hello</div>
        <button @click="makeBgDarker">+</button>
    </div>
      
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      相关资源
      最近更新 更多