Vue页面间通信传值的方法

页面跳转与传值

routes路由:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export default new Router({
routes: [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/deitail',
name: 'deitail',
component: deitail
}
]
})

使用<router-link>进行跳转和传值

1
2
<router-link :to="{name:'deitail',params:{freezeMon:'2017-10',owerName:'西安'}}" tag="div" >
</router-link>

取值时:

1
<h1>{{$route.params.freezeMon}}</h1>

小结:router-link跳转传值要注意的地方

  • to前面要加 :
  • to后面{中的name值要与路由中的name值一致

二、使用$router.push()

query写法

传值的路由

1
2
3
this.$router.push({
path: "/login?uname=" + this.userName
});

传值路由第二种写法

1
2
3
4
5
6
this.$router.push({
path: "/login",
query: {
uname: this.userName
}
});

接收值的路由

1
console.log("接收过来的值为:" + this.$route.query.uname);        //这里是$route 没有r----


params写法

传值路由第一种写法(还是会将参数显示在地址栏中)

1
2
3
this.$router.push({
path: "/login/" + this.userName
});

传值路由的第二种写法(不会将参数显示在地址栏中)

1
2
3
4
5
6
this.$router.push({
name: "login",
params: {
uname: this.userName
}
});

接收值的路由

1
console.log("接收过来的值为:" + this.$route.params.uname);

注意:在使用params传递参数的时候,我们需要在router的对象里面,找到当前的这个路由,然后去更改它的 path

1
2
3
4
5
{
path: "/login/:uname", //代表当前url跳转的路径
component: login, //代表在当前这个路径下面,我们如何显示组件(显示那一个组件)
name: "login" //给当前路由取一个别名
}

上面的path后面是 /login/:uname ,这一个是我们的一个路径变量,前面的login代表路由,而后面:uname代表的是变量