[Vuejs]-Vue.js with Vue-Router AJAX call before application starts

0👍

There is no shame in using jQuery, for example, for ajax calls.

If you have a global store (using vuex here) you can set a boolean to true after the first TryLogin, so you don’t call it more than once after further route changes. Something like that:

import Vue from 'vue';
import Router from 'vue-router';
import store from './store';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      component: Home,
    },
    {
      path: '/profile',
      component: Profile,
      meta: {loggedIn: true}
    },
    {
      path: '/signup',
      component: Signup,
      meta: {loggedOut: true},
    }
  ],
});

router.beforeEach(async (to, from, next) => {
  if (!store.state.userLoaded) {
    await $.get('/api/account').then(
      // Gets the user (or null) from the server, and
      // set userLoaded to true in any case
      user => store.commit('updateUser', user),
      err => console.error(err)
    }
  }

  // Check if the user needs to be logged in
  if (to.meta.loggedIn && !store.state.user) {
    return next ({path: '/login', query: {redirectTo: to.fullPath}});
    // Check if the user needs to be logged out
  } else if (to.meta.loggedOut && store.state.user) {
    return next ({path: '/'});
  }
  // We can proceeed
  next();
}

export default router;

The store.commit('updateUser', user) will set userLoaded to true regardless of whether the user is actually logged in.

Here is an example of the vuex store used:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
    userLoaded: false
  },
  mutations: {
    updateUser: (state, user) => {
      state.user = user;
      state.userLoaded = true;
    }
  }
});

And the main vue file:

import router from './router';
import store from './store';

new Vue({
    router,
    store
}).$mount("div#application")

Leave a comment