
image.png
1
我們可以直接在路由配置文件(/src/router/index.js)中寫鉤子函數(shù)。但是在路由文件中我們只能寫一個(gè)beforeEnter,就是在進(jìn)入此路由配置時(shí)。先來(lái)看一段具體的代碼:
{
path:'/params/:newsId(\\d+)/:newsTitle',
component:Params,
beforeEnter:(to,from,next)=>{
console.log('我進(jìn)入了params模板');
console.log(to);
console.log(from);
next();
},
三個(gè)參數(shù):
to:路由將要跳轉(zhuǎn)的路徑信息,信息是包含在對(duì)像里邊的。
from:路徑跳轉(zhuǎn)前的路徑信息,也是一個(gè)對(duì)象的形式。
next:路由的控制參數(shù),常用的有next(true)和next(false)。
2寫在模板中的鉤子函數(shù)
beforeRouteEnter:在路由進(jìn)入前的鉤子函數(shù)。
beforeRouteLeave:在路由離開前的鉤子函數(shù)。
export default {
name: 'params',
data () {
return {
msg: 'params page'
}
},
beforeRouteEnter:(to,from,next)=>{
console.log("準(zhǔn)備進(jìn)入路由模板");
next();
},
beforeRouteLeave: (to, from, next) => {
console.log("準(zhǔn)備離開路由模板");
next();
}
}
</script>
2 404頁(yè)面
1 router
{
path:'*',
component:Error
}
2 html
<template>
<div>
<h2>{{ msg }}</h2>
</div>
</template>
<script>
export default {
data () {
return {
msg: 'Error:404'
}
}
}
</script>
<router-link to="/bbbbbb">我是瞎寫的</router-link> |
3編程式導(dǎo)航
<button @click="goback">后退</button>
<script>
export default {
name: 'app',
methods:{
goback(){
this.$router.go(-1);
}
}
}
</script>
router.go(1):代表著前進(jìn),用法和后退一樣,我在這里就不重復(fù)碼字了(碼字辛苦希望大家理解)。
this.$router.push(‘/xxx ‘)
<button @click="goHome">回到首頁(yè)</button>
export default {
name: 'app',
methods:{
goback(){
this.$router.go(-1);
},
goHome(){
this.$router.push('/');
}
}
}
參考網(wǎng)址:http://jspang.com/2017/04/13/vue-router/#9