简体   繁体   中英

Storing data in Vue.js with vue-router

I have a Vue.js project which installed the vue-router to control the "pages" and axios for calling API.

Here is my routing

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

in the testingPage, I will call API to get the data for rendering the pages like this.

<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>

When but here is a problem , every time use click the link and redirect to this "page" , the api will be called. The API will only update 1-2 times per month.

Can I only call once ,then store the result and make it wont call API again until use refresh the page or open the page in the new browser / tab ?

How about using vuex? On mounting main App(it will be mounted only once.), you can store data in vuex stores.

Plus, if you want to keep your state in multiple tab I recommend you to use localStorage .

Check this out: Multiple Tab LocalStorage single user Use case

And there is libray for vuex + localstorage: https://www.npmjs.com/package/vuex-localstorage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM