使用 vue-router 在 Vue.js 中存储数据

Storing data in Vue.js with vue-router

我有一个 Vue.js 项目,它安装了 vue-router 来控制 "pages" 和调用 API 的 axios。

这是我的路线

routes: [
  {
    path: '/',
    name: 'LandingPage',
    component: LandingPage
  },
  {
    path: '/test',
    name: 'test',
    component: testing
  }
]

在testingPage中,我会调用API来获取渲染页面的数据。

<template>
  <div>
    {{title}}
  </div>
</template>
<script>
 import axios from 'axios'

 export default {
   name: 'app',
   data: function () {
     return {
       result: [],
       title:""
     }
   },
   methods: {
     fetchResult: function () {
       axios.get('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
         this.result = response;
         this.title = response.data.title
         console.log(response);
       }, (error) => {
         console.log(error)
       })
     }
   },
   mounted: function () {
     this.fetchResult()
   }
 }
</script>

但是这里出现问题时,每次使用点击link并重定向到这个"page",都会调用api。 API每月只会更新1-2次。

我可以只调用一次,然后存储结果并使其不会再次调用 API 直到使用刷新页面或在新的浏览器/选项卡中打开页面吗?

使用vuex怎么样?主App挂载时(只会挂载一次),可以在vuex store中存储数据

此外,如果您想在多个选项卡中保持状态,我建议您使用 localStorage

看看这个:

还有用于 vuex + localstorage 的库: https://www.npmjs.com/package/vuex-localstorage