有什么方法可以“监视"Vuejs 中的本地存储? [英] Is there any way to 'watch' for localstorage in Vuejs?

查看:41
本文介绍了有什么方法可以“监视"Vuejs 中的本地存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试监视本地存储:

模板:

<p>token - {{token}}</p>

脚本:

计算:{令牌(){返回 localStorage.getItem('token');}}

但它不会改变,当 token 改变时.只有在刷新页面之后.

有没有不使用 Vuex 或状态管理的方法来解决这个问题?

解决方案

没问题!我认为最好的做法是使用 getter/setter 语法来包装本地存储.>

这是一个工作示例:

HTML:

{{令牌}}<button @click="token++">+ </按钮>

JS:

new Vue({el: '#app',数据:函数(){返回 {获取令牌(){return localStorage.getItem('token') ||0;},设置令牌(值){localStorage.setItem('token', value);}};}});

还有一个 JSFiddle.

I'm attempting to watch for localstorage:

Template:

<p>token - {{token}}</p>

Script:

computed: {
  token() {
    return localStorage.getItem('token');
  }
}

But it doesn't change, when token changes. Only after refreshing the page.

Is there a way to solve this without using Vuex or state management?

解决方案

Sure thing! The best practice in my opinion is to use the getter / setter syntax to wrap the localstorage in.

Here is a working example:

HTML:

<div id="app">
  {{token}}
  <button @click="token++"> + </button>
</div>

JS:

new Vue({
  el: '#app',
  data: function() {
    return {
      get token() {
        return localStorage.getItem('token') || 0;
      },
      set token(value) {
        localStorage.setItem('token', value);
      }
    };
  }
});

And a JSFiddle.

这篇关于有什么方法可以“监视"Vuejs 中的本地存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆