2

I'm currently using Vue Router's beforeEnter hooks to retrieve data for one of my routes.

{
    path: '/A',
    beforeEnter: (to, from, next) => {
      loadData();
      next();
    },
}

A simple example of the flow would be:

Navigate to Route A --> Loading Data
Navigate to Route B
Navigate to Route A --> Loading Data again

How can i prevent the second & obsolete API Call? since it's not important that the data is that up-to-date. I could do: if (!dataIsAlreadyThere) loadData(), but this is somehow not nice to have with many routes. Are there any other solutions or ideas out there?

3
  • Can you make this check in something close to loadData instead? For example, all the data fetching routines go through the same place that acts as a (or interacts with) Cache Manager. Commented Jan 15, 2018 at 16:44
  • yes of course that would be better then, but this is kind of also part of my question. If any solution exists to only make api calls if necessary, which would be kind of similar to your cache manager Commented Jan 15, 2018 at 16:58
  • @Berni use eventbus or vuex for state management Commented Jan 15, 2018 at 18:02

1 Answer 1

2

The following should work according to some clues from the vue and vue-router documentations:

  1. Wrap your router-view inside a keep-alive element

  2. Fetch the API inside the mounted hook of your component:

    mounted () { this.data = loadData() }

In theory, this should only mount the component once and keep its state alive, even when the router is switching components inside the router-view.

Note that this is not the preferred way which vuejs or the vue-router itself suggest. Vue suggest using external state management like vuex.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.