一、<router-link的使用

<router-link>组件支持用户在具有路由功能中的点击导航。通过to属性指向目标地址,默认渲染成正确的a标签

1.to属性 字符串或是对象类型

点击会立刻把内部to值传送到router.push() (解释:router.push(location) 就相当于我们用鼠标点击了location这个a链接一样,本文后面有对router.push()方法的详细讲解

例:<router-link to="/Home">Home</router-link>

<router-link :to="{name:'Home'}">Home</router-link>

渲染结果:<a href="Home">Home</a>

二、router.push(location)

讲解:router.push(location) 就相当于我们用鼠标点击了location这个a链接一样

除了使用<router-link> 创建 a标签来定义导航链接,我们还可以借助 router的实例方法,通过编写代码来实现,案例如下

router.push(location)

想要导航到不同的 URL,则使用 router.push() 方法。这个方法会向 history栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。
在一个带有<router-link>template中,当用户点击该链接,实质上是在内部调用了router.push()方法(解释:所以我们经常说router.push(location) 就相当于我们用鼠标点击了location这个a链接一样),因此,显示调用router.push(…)实质上与<router-link :to="..."> 是一致的,只不过一个是标签用法,一个是脚逻辑用法

声明式:<router-link :to="...">
编程式: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) { //取得route路由时带过来的参数
    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 关键字

设置 replace 属性的话,当点击时,会调用router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。即使点击返回按钮也不会回到这个页面。它所执行的是替换掉当前路由的历史记录

  • 类型:boolean
  • 默认值:false
//第一种写法
this.$router.push({path: '/home', replace: true})
// 第二种写法:如果是声明式就是像下面这样写:
<router-link :to="..." replace></router-link>
//第三种写法 编程式:
router.replace(...)

综合案例

let queryData = {
  id: this.groupID,
  name: this.groupName,
  tags: 30
}
this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});

本文转载自:https://www.jianshu.com/p/1aa7ff492430