Vue router(传参)最常用的几种

551 阅读1分钟

第一种:

这一种就是根据页面的路径来跳转的 如: path: '/Home/miun.vue'后面的query是跳转的时候携带的参数 这里携带了两个参数 一个是this.arr数组 一个是this.id是id 每个参数用豆号隔开

<div @click="link1()">跳转1</div>

link1(){    this.$router.push({
         path: '/Home/miun.vue',query: {arr: JSON.stringify(this.arr) , id: this.id}
    })},

然后在跳转的页面'/Home/miun.vue'里面打印传过来的数据

console.log(this.$route.query.id);
console.log(JSON.parse(this.$route.query.arr)); 

第二种:

这一种也是一样根据页面路径跳转 唯一不一样的是 传参得方式不一样这种方式是在页面路径的后面加个?号 ,?号后面的就是参数 注意拼接 参数的名字arr= 要在引号里面 +上需要传递的参数就可以了,

<div @click="link2()">跳转2</div>

link2(){    this.$router.push({
        path: '/Home/miun.vue?arr='+ JSON.stringify(this.arr) + '&id=' +this.id
    })},

       注意这里传多个参数的时候 第一个参数的后面加一个+号  引号里面是第二个参数的名字 但是名字前面一定要加&符号 

在/Home/miun.vue页面里面打印 

console.log(this.$route.query.id);
console.log(JSON.parse(this.$route.query.arr)); 

第三种:

 这一种不一样的地方就是 前面的两种是根据页面路径跳转的 但是这种是根据页面的名字 name来跳转的
你的路由js文件里面是这样写的
{
     path: '/Home/miun.vue',
     name: 'miun',    //这个name就是miun.vue的名字
     component: miun,
},
<div @click="link3()">跳转3</div>

link3(){       this.$router.push({name: 'miun', query:{id: this.id}})}
  然后在/Home/miun.vue页面里面打印传过去的id
console.log(this.$route.query.id);

router-link传参

直接router-link实现路由跳转 这个 nema就是要跳转页面的名字
query: {id: id}为跳转时携带的参数

跳转 

然后在跳转的页面'/Home/miun.vue'里面的created函数里面打印传过来的数据

console.log(this.$route.query.id);

注意 :router和route的区别 传参是this.router,接收参数是this.router, 接收参数是this.route, 这里千万要看清了!!!