Vue + Axios 与 sessionStorage

Vue + Axios with sessionStorage

目标: 最初在 Vue 视图中通过 Axios 使用 Wordpress Rest API 加载帖子一次,并且仅在访问 Vue 网站的会话期间加载一次。

当前结果:我目前成功获取结果并将它们设置在sessionStorage中。它们显示正确。我想 know/learn 如果我正确地完成了这个并且以尽可能最好的方式优化了流程。我查阅了文档,我想我已经记下来了。

当前代码:

<script>
import Hero from "@/components/Hero.vue";
import axios from "axios";

export default {
  name: "About",
  components: {
    Hero,
  },
  data: function() {
    return {
      eatery: [],
    };
  },
  created() {
    axios
      .get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
      .then((response) => {
        sessionStorage.setItem("eatery", JSON.stringify(response.data));
      })
      .catch((error) => {
        window.alert(error);
      });
  },
  mounted() {
    if (sessionStorage.getItem("eatery")) {
      this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
    }
  },
};
</script>

我会在尝试加载它之前检查它是否在存储中。在您的情况下,它看起来像这样:

export default {
  name: "About",
  components: {
    Hero,
  },
  data: function() {
    return {
      eatery: [],
    };
  },
  loadEatery() {
    axios
      .get("//localhost:81/wp-json/wp/v2/posts?_embed&per_page=5&categories=2")
      .then((response) => {
        sessionStorage.setItem("eatery", JSON.stringify(response.data));
        return response.data;
      })
      .catch((error) => {
        console.error(error); // for debugging maybe
      });
  },
  mounted() {
    if (sessionStorage.getItem("eatery")) {
      this.eatery = JSON.parse(sessionStorage.getItem("eatery"));
    } else {
      loadEatery().then(data => this.eatery = data);
    }
  },
};