乐闻世界logo
搜索文章和话题

How to access async store data in vue-router for usage in beforeEnter hook?

1个答案

1

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.

  1. Set up Vuex Store
javascript
import 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); }); } } });
  1. Configure Vue Router
javascript
import 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 isLoggedIn state in the Vuex Store to indicate if the user is logged in, and provide an asynchronous checkLoginStatus action to simulate checking login status.
  • In the Vue Router configuration, we add a beforeEnter hook for protected routes (e.g., /secret). Within this hook, we call the checkLoginStatus action 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.

2024年7月15日 17:45 回复

你的答案