router.push()的使用,编程式导航到指定的路由等

  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() 方法可以接收以下参数:

  1. 路径字符串:直接指定要导航到的路径。

    this.$router.push('/about');
  2. 对象:可以包含 pathnameparamsquery 等属性。

    // 通过路径
     
    this.$router.push({ path: '/about' }); 
    
    // 通过路由名称 
    
    this.$router.push({ name: 'user', params: { userId: 123 } }); 
    
    // 包含查询参数 
    
    this.$router.push({ path: '/about', query: { plan: 'premium' } });

异步处理

router.push() 返回一个 Promise,因此可以用 thencatch 来处理导航后的逻辑:

this.$router.push('/home') .then(() => { 
     console.log('Navigation successful'); 

 }) .catch(err => { console.error('Navigation failed:', err); });

总结

  router.push() 是 Vue Router 提供的用于导航到新的路由的方法。它可以接收路径字符串、对象或者命名路由和参数,并支持返回一个 Promise 来处理导航后的逻辑。这使得在 Vue 应用中实现动态导航变得非常简单和灵活。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值