In Vue.js, we commonly use Vue Router for route management. In certain scenarios, we need to check or retrieve asynchronous data (such as user login status) before route navigation. Using the beforeEnter route guard hook can fulfill this requirement. Below, I will demonstrate how to access asynchronous data stored in Vuex within the beforeEnter hook using a specific example.
Assume we have a Vuex state management setup where user login status is stored. We need to verify if the user is logged in before accessing certain pages; if not, redirect them to the login page.
First, ensure you have set up Vuex and Vue Router in your project.
- Set up Vuex Store
javascriptimport Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { isLoggedIn: false }, mutations: { setLoggedIn(state, status) { state.isLoggedIn = status; } }, actions: { checkLoginStatus({ commit }) { return new Promise((resolve) => { // Simulating asynchronous request setTimeout(() => { const loggedIn = true; // Assuming user is logged in commit('setLoggedIn', loggedIn); resolve(loggedIn); }, 1000); }); } } });
- Configure Vue Router
javascriptimport Vue from 'vue'; import Router from 'vue-router'; import store from './store'; // Importing store Vue.use(Router); const router = new Router({ routes: [ { path: '/secret', name: 'SecretPage', component: () => import('./components/SecretPage.vue'), beforeEnter: (to, from, next) => { store.dispatch('checkLoginStatus').then(isLoggedIn => { if (!isLoggedIn) { next('/login'); // Redirecting to login page } else { next(); // Proceeding to target route } }); } }, { path: '/login', name: 'LoginPage', component: () => import('./components/LoginPage.vue') } ] }); export default router;
In this example:
- We define an
isLoggedInstate in the Vuex Store to indicate if the user is logged in, and provide an asynchronouscheckLoginStatusaction to simulate checking login status. - In the Vue Router configuration, we add a
beforeEnterhook for protected routes (e.g.,/secret). Within this hook, we call thecheckLoginStatusaction and decide to redirect to the login page or proceed based on the login status.
This approach ensures that users have their login status verified before accessing protected pages. This pattern is very useful for any scenario requiring asynchronous data handling before route navigation.