【问题标题】:Storing data in Vue.js with vue-router使用 vue-router 在 Vue.js 中存储数据
【发布时间】:2019-02-03 18:54:21
【问题描述】:

我有一个 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,直到使用刷新页面或在新的浏览器/标签中打开页面?

【问题讨论】:

    标签: javascript vue.js axios vue-router


    【解决方案1】:

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

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

    看看这个:Multiple Tab LocalStorage single user Use case

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

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2018-11-20
      • 2019-09-09
      • 2020-05-15
      • 2016-05-26
      • 2017-07-23
      • 1970-01-01
      • 2017-07-02
      • 2017-12-17
      相关资源
      最近更新 更多