router/index.js
import {createRouter,createWebHashHistory} from "vue-router";
import Login from "../components/views/login.vue";
import Register from "../components/views/register.vue";
import Nav from "../components/views/Nav.vue";
const router = new createRouter({
history:createWebHashHistory(), //注意此处函数与vue2不同
routes: [
/**/
{ path: '/', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/register', component: Register },
{ path: '/home', component: Nav, redirect:'/welcome', children: [
{ path: '/welcome', component: () => import("../components/views/Welcome.vue") }, //这样导入更简洁明了
],
},
]
});
// 如果要使用导航守卫,请使用以下代码
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
//异步请求前判断请求的连接是否需要token
// router.beforeEach((to, from, next) => {
// console.log("---路由变化---");
// console.log("from:"+JSON.stringify(from.fullPath));
// console.log("to:"+JSON.stringify(to.fullPath));
// console.log("-------------");
// if (to.path === '/'||to.path === '/login'||to.path === '/register') {
// next();
// } else {
// let token = localStorage.getItem('Token');
// if (token === null || token === '') {
// next('/login');
// } else {
// next();
// }
// }
// });
export default router;
main.js中:
import {createApp} from 'vue'
import App from './App.vue'
import router from './router' // 引入router
const app = createApp(App)
app.use(router) // 使用router
app.mount('#app')