如何使用 VueJS 将来自 API 的数据存储在 localStorage 中 [英] How to store data from an API in localStorage with VueJS

查看:25
本文介绍了如何使用 VueJS 将来自 API 的数据存储在 localStorage 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 VueJS 练习简单的 SPA 需要我监听一个 API 并将它的一些数据保存在浏览器的 localStorage 中,但是我对 VueJS 的经验还不是很丰富,所以我不知道如何采取具体的数据并将其保存到 LS,以便登录的用户稍后可以查看他们的信息.

My practice simple SPA with VueJS requires that I listen to an API and save some of its data in the localStorage of the browser, however I'm still not very experienced with VueJS so I don't know how to take the specific data and save it to LS so that logged users can see their info later.

API 检索了很多信息,现在我只想获取用户的电子邮件和姓名.

The API retrieves A LOT of information, for now I only want to get the email and name of the user.

这是目前为止的代码:

<script>
    import axios from 'axios';
  import jsonpAdapter from 'axios-jsonp';

  export default {
    data() {
      return {
        info: 'placeH',
        data: []
      }
    },
    mounted: function(){
      axios({
        url: 'APIplaceholder'
        adapter: jsonpAdapter
      }).then((res) => {

      });
    }
  }
</script>

我现在的问题是我不知道如何只选择我想要的特定信息(API返回很多信息,但我只需要电子邮件和姓名)然后将其保存到localStorage.

My problem right now is that I don't know how to select only the specific information (the API returns a lot of info, but I only need the email and name) that I want and then save it to localStorage.

我认为最好也将其保存到 LS 中的 JSON 文件中.

I think the best would also be to save it to a JSON file in the LS.

推荐答案

你得到一个 response 对象,该对象具有 data 属性,表示请求的 user如下:

You are getting a response object which has data property that represents a requested user as follow :

mounted: function(){
  axios({
    url: 'APIplaceholder'
    adapter: jsonpAdapter
  }).then((res) => {     
        localStorage["name"]=res.data.name
        localStorage["email"]=res.data.email
  });
}

这篇关于如何使用 VueJS 将来自 API 的数据存储在 localStorage 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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