如何在不同的屏幕上获取本地存储数据?

How to fetch localstorage data in different screen?

我正在使用 Ionic 并将用户的首选项保存在本地存储中。

现在,我想在此人的个人资料中显示此数据(因此在 不同的屏幕/页面 中),但我不知道如何获取此数据数据.

有人可以帮我吗?

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'fav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = '';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});

// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage

这是我的代码笔: https://codepen.io/CrocoDillon/pen/pIlKB

只要您在同一个域中,就应该可以访问同一个 localStorage 对象。所以这应该有效:

var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
const favorites = JSON.parse(localStorage.getItem('favorites')) || [];

localStorage.getItem('favorites')本身就是一个存取器