详解 router.push()
举报
SHQ1874009
发表于 2023/01/07 12:25:34
2023/01/07
【摘要】 一、前言在Vue2.0路由跳转中,除了使用 一、前言 在Vue2.0路由跳转中,除了使用 router.push(location) 想要导航到不同的 URL,使用 router.push 方法。这个方法会向 history 栈添加一个新记录,所以,当用户点击浏览器后退按钮时,可以返回到之前的 URL。 当你点击 声明式: 编程式:router.push(...) 该方法的参数可以是一个字符串路径,或者一个描述地址的对象。 // 字符串 router.push('home') // 对象 this.$router.push({path: '/login?url=' + this.$route.path}); // 命名的路由 router.push({ name: 'user', params: { userId: 123 }}) // 带查询参数,变成/backend/order?selected=2 this.$router.push({path: '/backend/order', query: {selected: "2"}}); // 设置查询参数 this.$http.post('v1/user/select-stage', {stage: stage}) .then(({data: {code, content}}) => { if (code === 0) { // 对象 this.$router.push({path: '/home'}); }else if(code === 10){ // 带查询参数,变成/login?stage=stage this.$router.push({path: '/login', query:{stage: stage}}); } }); // 设计查询参数对象 let queryData = {}; if (this.$route.query.stage) { queryData.stage = this.$route.query.stage; } if (this.$route.query.url) { queryData.url = this.$route.query.url; } this.$router.push({path: '/my/profile', query: queryData}); 设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。点击返回按钮时,不会返回到这个页面。 //加上replace: true后,它不会向 `history` 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。 this.$router.push({path: '/home', replace: true}) //如果是声明式就是像下面这样写: // 编程式: router.replace(...) 二、综合案例 this.$router.push( { path: '/coach/' + this.$route.params.id, query: queryData } ); 点击返回上一页 methods:{ goback(){ this.$router.go(-1) } } 点击跳转到/Foo2页面 ToLink1(){ this.$router.push('/foo2') } 或者this.$router.push({name:'Foo2'})对象的方法。 三、拓展阅读 《Vue进阶(幺叁捌):vue路由传参的几种基本方式》 推荐 华为开发者空间发布 让每位开发者拥有一台云主机 【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com NAT 点赞 收藏 关注作者