1.在src/router/index.js加如下代码
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
//导入各页面组件
import Login from '@/views/login.vue'
import Home from '@/views/home.vue'
import User from '@/views/user/index.vue'
import Log from '@/views/log/index.vue'
import ErrLogin from '@/views/errLogin/index.vue'
Vue.use(Router)
const router = new Router({
routes: [
{ path: '/login', component: Login },
{ path: '/home', component: Home, meta: { requiresAuth: true } },
{ path: '/log', component: Log, meta: { requiresAuth: true } },
{ path: '/user', component: User, meta: { requiresAuth: true } },
{ path: '/errLogin', component: ErrLogin, meta: { requiresAuth: true } },
// 其他路由
]
});
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.isAuthenticated; // 从 Vuex 中获取认证状态
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next({ path: '/login' }); // 重定向到登录页
} else {
next(); // 继续访问
}
});