router.push()
是在 Vue.js 中用于导航到不同路由的一个方法,尤其是在使用 Vue Router 作为路由管理器时。这个方法允许你在代码中以编程的方式导航到一个新的路由。
使用方法:
router.push()
有多种使用方式,可以接收一个字符串路径、一个对象或者是带有路由名称和参数的对象。
1. 传递字符串路径
this.$router.push('/home');
- 导航到路径
/home
。
2. 传递对象
this.$router.push({ path: '/home' });
- 导航到路径
/home
。
3. 使用路由名称和参数
this.$router.push({ name: 'user', params: { userId: 123 } });
- 导航到命名路由
user
,并传递参数userId
。
4.跳转路由[选择条]
router.push(
startPage == '0' ? '/homePage' : startPage == '1' ? '/main/testSetting' : '/main/testTemplate' //使用了条件(三元)运算符来决定导航的目标路径:
);
router.push()
方法用于编程式导航。- 使用条件(三元)运算符判断
startPage
的值:- 如果
startPage
是'0'
,导航到/homePage
。 - 如果
startPage
是'1'
,导航到/main/testSetting
。 - 否则,导航到
/main/testTemplate
。
- 如果
4.完整示例
假设你有一个 Vue 组件,希望在点击按钮时导航到不同的页面:
<template>
<div>
<button @click="goToHome">Go to Home</button>
<button @click="goToUser(123)">Go to User 123</button>
</div>
</template>
<script>
export default {
methods: {
goToHome() { this.$router.push('/home'); },
goToUser(userId) {
this.$router.push({ name: 'user', params: { userId: userId } });
}
}
};
</script>
参数解析
router.push()
方法可以接收以下参数:
-
路径字符串:直接指定要导航到的路径。
this.$router.push('/about');
-
对象:可以包含
path
、name
、params
和query
等属性。// 通过路径 this.$router.push({ path: '/about' }); // 通过路由名称 this.$router.push({ name: 'user', params: { userId: 123 } }); // 包含查询参数 this.$router.push({ path: '/about', query: { plan: 'premium' } });
异步处理
router.push()
返回一个 Promise
,因此可以用 then
和 catch
来处理导航后的逻辑:
this.$router.push('/home') .then(() => {
console.log('Navigation successful');
}) .catch(err => { console.error('Navigation failed:', err); });
总结
router.push()
是 Vue Router 提供的用于导航到新的路由的方法。它可以接收路径字符串、对象或者命名路由和参数,并支持返回一个 Promise
来处理导航后的逻辑。这使得在 Vue 应用中实现动态导航变得非常简单和灵活。