尝试从本地存储检索

尝试从本地存储检索

本文介绍了尝试从本地存储检索/获取数据时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        const headers = new Headers({
          'access_token' : accToken,
          'Content-Type': 'application/json',
        });






        axios.post(baseURI, data, {
          headers: headers
        })
        .then((response) => {
          this.users = response;

        }, (error) => {
          if (error) {
            this.errorMessage = error.response.data.message;
          }
        }).catch(error => {
          //this.errorMessage = error.response.data;
        })
    },

尝试从本地存储检索/获取数据时出错?

Error when trying to retrieve/get data from the local storage?

我使用 vuejs 创建了一个登录表单,其中的数据存储在本地存储中,但我想从本地存储中检索数据以进行搜索.

I have created a login form using vuejs from which data is getting stored in the local storage, but I want to retrieve data from local storage for search purpose.

在本地存储中,我附上了截图.在我的代码中尝试获取值的位置.

In the localstorage, i have attached screenshot. Where in my code tried getting the values.

推荐答案

在将对象存储到 localStorage 之前将其编码为 JSON.原因是许多浏览器将 localStorage 视为键/值对 严格用于字符串意味着您不能存储复杂的数据类型,例如对象.通过调用 JSON.Stringify(obj),您将您的对象转换为带有 JSON 的字符串.然后,当您访问数据时,您需要使用 JSON.parse(str) 将其转换回对象.

Encode your object to JSON before storing it in localStorage. The reason being is that many browsers treat localStorage as a key/value pair strictly for strings meaning that you cannot store complex data types such as an object. By calling JSON.Stringify(obj) you are converting your object to a string with JSON. Then later when you access the data you need to convert it back to an object by using JSON.parse(str).

例如,在您的代码中,您可能希望更改这一行

For example, in your code, you would want to change this line

localStorage.setItem('loggedinUser', response.data.access_token);

为此,您将对象编码为字符串

To this, so you encode the object as a string

localStorage.setItem('loggedinUser', JSON.stringify(response.data.access_token));

然后,当您检索数据时,您将从中更改 getter

Then when you retrieve the data you would change your getter from

var searchItem = localStorage.getItem('anonymous_id');

var searchItem = JSON.parse(localStorage.getItem('anonymous_id'));

这样你就可以将字符串解析回正确的数据类型

That way you are parsing the string back into a proper datatype

这篇关于尝试从本地存储检索/获取数据时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:05