1、查了一下網上的資料,發現以下方法有效
history.pushState(null, null, document.URL); window.addEventListener('popstate', function () { history.pushState(null, null, document.URL); });
2、可是,有時候不能直接禁用,而是要返回指定的路由地址,於是:
mounted() { if (window.history && window.history.pushState) { // 向歷史記錄中插入了當前頁 history.pushState(null, null, document.URL); window.addEventListener('popstate', this.goback, false); } }, destroyed() { window.removeEventListener('popstate', this.goback, false); },
其中this.goback()是mothods中的方法,可以自定義返回地址,例如:
goback: function() { this.$router.push({ path: '/orderdetails', }); history.pushState(null, null, document.URL); },
3、以上兩個方法出現的情況都是因為瀏覽器有記錄跳轉路由,因為之前基本路由跳轉都是用的router.push(),后來看了一下官網才知道,其實可以直接使用router.replace(),跟router.push很像,唯一的不同就是,他不會向history添加新記錄,而是跟他的方法名一樣,替換掉當前的history記錄,他有兩種方式:
①:聲名式
<router-link :to="..." replace>
②:編程式
router.replace(...)
需要注意的是,如果目的地和當前路由相同,只有參數發生了改變,則需要使用beforeRouteUpdate來響應這個變化
由於使用路由參數時,原來的組件實例會被復用,組件的生命周期鈎子也不會再被調用。
所以,復用組件時,想對路由參數的變化做出響應的話,可以簡單的watch(檢測變化)$route對象:
const User = { template: '...', watch: { '$route' (to, from) { // 對路由變化作出響應... } } }
或者使用2.2中引入的beforeRouteUpdate導航守衛:
const User = { template: '...', beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() } }
捕獲所有路由或404 Not found路由
{ // 會匹配所有路徑 path: '*' } { // 會匹配以 `/user-` 開頭的任意路徑 path: '/user-*' }
當使用通配符路由時,請確保路由的順序是正確的,也就是說含有通配符的路由應該放在最后。路由 { path: '*' } 通常用於客戶端 404 錯誤。
當使用一個通配符時,$route.params 內會自動添加一個名為 pathMatch 參數。它包含了 URL 通過通配符被匹配的部分:
// 給出一個路由 { path: '/user-*' } this.$router.push('/user-admin') this.$route.params.pathMatch // 'admin' // 給出一個路由 { path: '*' } this.$router.push('/non-existing') this.$route.params.pathMatch // '/non-existing'
