首页 > 解决方案 > 使用 vue-router 在 Vue.js 中存储数据

问题描述

我有一个 Vue.js 项目,它安装了 vue-router 来控制“页面”和 axios 以调用 API。

这是我的路线

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>

但是这里出现问题时,每次使用单击链接并重定向到此“页面”时,都会调用该 api。API 每月只会更新 1-2 次。

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

标签: javascriptvue.jsaxiosvue-router

解决方案


用vuex怎么样?在挂载主应用程序时(它只会挂载一次。),您可以将数据存储在 vuex 商店中。

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

看看这个:Multiple Tab LocalStorage 单用户用例

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


推荐阅读