const router = new VueRouter({ ... }
//前置的钩子函数 最后要执行next()才会跳转
router.beforeEach((to, from, next) => {
// ...
})
//后置的钩子函数 已经跳转了不需要next
router.afterEach((to, from) => {
// ...
})
主要是简单介绍一下,路由守卫主要用于检验是否登录了,没登录就跳转到登录页面不让他在其他页面停留,但是现在这种处理主要的都用请求的全局拦截来做了。大致了解一下路由守卫即可
<!DOCTYPE html>
<html>
<head>
<title>路由守卫</title>
</head>
<body>
<div id="app">
</div>
<script type="text/javascript" src="vue.js"></script>
<!-- 引入路由插件 -->
<script type="text/javascript" src="vue-router.js"></script>
<script type="text/javascript">
var Nav={
template:`
<div>
<router-view></router-view>
<router-link :to="{name:'nav.index'}">首页</router-link>
|
<router-link :to="{name:'nav.pensonal'}">个人中心</router-link>
|
<router-link :to="{name:'nav.message'}">资讯</router-link>
|
<router-link :to="{name:'nav.mine'}">我的</router-link>
</div>
`,
}
var Index={
template:`
<div>首页</div>
`,
}
var Pensonal={
template:`
<div>个人中心</div>
`,
}
var Message={
template:`
<div>资讯</div>
`,
}
var Mine={
template:`
<div>我的</div>
`,
}
//安装路由插件
Vue.use(VueRouter);
//创建路由对象
var router= new VueRouter({
//配置路由对象
routes:[
{
path:'',
redirect:'/nav'
},
{
path:'/nav',
name:'nav',
component:Nav,
//嵌套路由增加这个属性
children:[
//配置我们的嵌套路由
{path:'',redirect:'/nav/index'},
{path:'index',name:'nav.index',component:Index},
{path:'pensonal',name:'nav.pensonal',component:Pensonal},
{path:'message',name:'nav.message',component:Message},
{path:'mine',name:'nav.mine',component:Mine},
]
}
]
})
new Vue({
el:'#app',
router,
template:`
<div>
<router-view></router-view>
</div>
`,
data(){
return {
loginstate:true
}
},
methods:{
},
mounted(){
//利用路由守卫做当跳转首页时可直接跳转,跳转其他页面要等待两秒才可以跳转
router.beforeEach((to,from,next)=>{
console.log(to)
if(to.path=='/nav/index'){
next()
}else{
setTimeout(function(){
next()
},2000)
}
})
}
})
</script>
</body>
</html>