0
votes

Trying to figure out what is the best way to fetch some data before navigating to some routes that I have.

My routes are:

let routes = [
    {
        path: '/',
        component: require('./views/Home.vue')
    },
    {
        path: '/messages',
        component: require('./views/Messages.vue'),
    },
    {
        path: '/posts',
        component: require('./views/Post.vue'),
    },
    {
        path: '/login',
        component: require('./views/Login.vue')
    },
    {
        path: '/dashboard',
        component: require('./views/Dashboard.vue'),
    }
];

For /messages, /posts and /dashboard I want to fetch some data and while doing that show a spinner.

Vue-router docs suggest to use beforeRouteEnter, Fetching Before Navigation

beforeRouteEnter (to, from, next) {
    getPost(to.params.id, (err, post) => {
        next(vm => vm.setData(err, post))
    })
}

But my question is, must I implement this fetch logic in all my three view components? Since it's the same data being fetched I don't want to repeat the logic in every component.

The beforeRouteEnter isn't called in my root component where I have this <router-view></router-view> otherwise I feel that it would be the best place to have this logic.

I'm really new to vue and this one is a really hard nut to crack for me.

1

1 Answers

2
votes

Are you aware of vuex? Since you need to share the same data on three different pages, which sounds like a job for vuex store. Basically you can import the store into your router, and set data in the store instead of on the component, and then you can conditionally fetch the data by checking the status of the data in the store and if the data already exists, don't fetch. Something like the following:

import store from './store'

beforeRouteEnter (to, from, next) {
  if (store.state.post === null) {
    getPost(to.params.id, (err, post) => {
        store.dispatch('setPost', post)
        next()
    })
  }
}

Assume your store has a state called post and action called setPost.

const store = new Vuex.Store({
  state: { post: null },
  actions: {
    setPost ({ commit }, post) {
      // set the post state here
    }
  }
})