路由配置文件中的鉤子函數(shù)

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容