运行显示login页面,手动在浏览器中application中输入token值,即可访问carts、goods页面
<div id="root">
<router-view></router-view>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.4.9/dist/vue-router.js"></script>
<script>
// 定义组件
const adminIndex = {
template: `
<div class="container">
<div class="menu">
<h1>
<router-link to="/carts">购物车</router-link>
</h1>
<h1>
<router-link to="/goods">商品</router-link>
</h1>
</div>
<div class="main">
<router-view></router-view>
</div>
</div>
`
}
const carts = {
template: `<h1>购物车区域</h1>`
}
const goods = {
template: `<h1>商品区域</h1>`
}
// 定义路由
const router = new VueRouter({
// 声明路由模式
mode: 'hash',
// 声明路由
routes: [
// 明确:只要是【/】就会显示adminIndex组件数据,再监控范围坑中显示
// 然后:【/sdfd】能匹配到父 - 在监控范围坑显示,不能匹配到子-则子不显示
// 然后:【/goods】能匹配到父 - 在监控范围坑显示,能匹配到子-子切记不在监控范围显示,而是再付坑里面 如果父没有坑,不显示
{
path: '/',
component: adminIndex,
children: [
{ path: 'carts', component: carts },
{ path: 'goods', component: goods }
]
},
{ path: '/login', component: { template: `<h1>登录页</h1>` } }
]
})
// 导航守卫:监控网址变化触发
// 切记:不写next就会拦截视图渲染
router.beforeEach((newData, oldData, next) => {
if (newData.path == '/404' || newData.path == '/login') {
next()
} else {
let token = localStorage.getItem('token')
if (token) {
next()
} else {
next({ path: '/login' })
}
}
})
const vm = new Vue({
router,
el: '#root',
data: {}
})
</script>
<style>
* {
padding: 0px;
margin: 0px;
}
.container {
width: 100%;
height: 100%;
background: #ccc;
display: flex;
}
.menu {
width: 200px;
height: 100%;
background: green;
}
.main {
flex: 1;
background: pink;
}
</style>