在 Vue 中,編程式導航是通過 JavaScript 代碼(而非 <router-link>
標簽)動態控制路由跳轉的核心方式。這個方法依賴于 Vue Router 提供的 API,能更靈活地處理復雜場景(如異步操作、條件跳轉等)。
一、核心方法
Vue Router 提供了以下方法實現編程式導航:
方法 | 作用 |
---|---|
router.push() | 跳轉新頁面,會向瀏覽器歷史記錄添加新條目(可后退) |
router.replace() | 替換當前頁面,不會留下歷史記錄(不可后退) |
router.go(n) | 前進/后退 n 步(正數前進,負數后退) |
router.back() | 后退一步(等價于 router.go(-1) ) |
router.forward() | 前進一步(等價于 router.go(1) ) |
二、router.push()
詳解
這是最常用的方法,支持多種參數格式:
1. 路徑字符串
// 跳轉到指定路徑
this.$router.push('/user');
2. 對象描述(推薦)
// 通過路徑跳轉
this.$router.push({ path: '/user' });// 通過命名路由跳轉(需在路由配置中定義 name)
this.$router.push({ name: 'UserProfile', params: { userId: 123 } // 動態參數(需路由配置占位符)
});
3. 攜帶參數
-
query
參數(URL 可見,適合非敏感數據):this.$router.push({path: '/user',query: { id: 1, name: '王博涵' } }); // URL: /user?id=1&name=John
-
params
參數(需路由配置占位符,URL 更簡潔):// 路由配置 { path: '/user/:userId', name: 'User', component: User }// 跳轉代碼 this.$router.push({name: 'User', // 必須使用命名路由params: { userId: 123 } }); // URL: /user/123
三、router.replace()
使用
與 push
類似,但不會留下歷史記錄:
// 替換當前頁面(不可后退)
this.$router.replace({ path: '/login' });
四、router.go()
控制歷史記錄
// 后退一步
this.$router.go(-1);// 前進兩步
this.$router.go(2);
五、動態路由參數處理
在目標組件中,通過 $route.params
或 props
接收參數:
1. 通過 $route
獲取
// 目標組件中
export default {mounted() {const userId = this.$route.params.userId;console.log(userId); // 123}
}
2. 通過 props
解耦(推薦)
// 路由配置中啟用 props
{ path: '/user/:userId', component: User, props: true
}// 目標組件聲明 props
export default {props: ['userId'],mounted() {console.log(this.userId); // 123}
}
六、高級用法
1. 異步跳轉處理
this.$router.push('/target').catch(error => {// 處理導航錯誤(如重復跳轉同一路由)if (error.name === 'NavigationDuplicated') {console.log('重復跳轉');}
});
2. 導航守衛結合
在全局或路由獨享守衛中控制跳轉:
// 全局前置守衛
router.beforeEach((to, from, next) => {if (to.path === '/admin' && !isAdmin) {next('/login'); // 中斷跳轉并重定向} else {next();}
});
七、注意事項
params
必須使用name
:若使用params
,跳轉時必須通過name
而非path
。- 路由配置匹配:確保路由路徑中包含參數占位符(如
/user/:id
)。 - 可選參數:在路由路徑中使用
?
修飾符定義可選參數:{ path: '/user/:id?' } // id 為可選
八、完整示例
1. 路由配置
// router.js
import Vue from 'vue';
import VueRouter from 'vue-router';Vue.use(VueRouter);const routes = [{path: '/user/:userId',name: 'User',component: () => import('./User.vue'),props: true}
];const router = new VueRouter({ routes });
export default router;
2. 跳轉代碼
// 在組件方法中
methods: {navigateToUser() {this.$router.push({name: 'User',params: { userId: 123 }});}
}
3. 目標組件
<!-- User.vue -->
<template><div>User ID: {{ userId }}</div>
</template><script>
export default {props: ['userId']
};
</script>