$router
和$route
的区别
//$router : 是路由操作对象,只写对象
//$route : 路由信息对象,只读对象
//操作 路由跳转
this.$router.push({
name:'hello',
params:{
name:'word',
age:'11'
}
})
//读取 路由参数接收
this.name = this.$route.params.name;
this.age = this.$route.params.age;
query传递参数
//query传参,使用name跳转
this.$router.push({
name:'second',
query: {
queryId:'20190612',
queryName: 'query'
}
})
//query传参,使用path跳转
this.$router.push({
path:'second',
query: {
queryId:'20190612',
queryName: 'query'
}
})
//query传参接收second.vue
this.queryName = this.$route.query.queryName;
this.queryId = this.$route.query.queryId;
//接受参数
console.log('query',this.$route.query)
this.queryName = this.$route.query.queryName;
this.queryId = this.$route.query.queryId;
//路由 index.js
{
path:'/second',
name:'second',
component:()=>import('@/view/second')
}
params传递参数
//params传参 使用name
this.$router.push({
name:'second',
params: {
id:'20190612',
name: 'query'
}
})
//params接收参数
this.id = this.$route.params.id ;
this.name = this.$route.params.name ;
//路由
{
path: '/second/:id/:name',
name: 'second',
component: () => import('@/view/second')
}
//接受参数second.vue
console.log('params',this.$route.parmas)
this.id = this.$route.params.id;
this.name = this.$route.params.name;
//路由 index.js
{
path:'/second',
name:'second',
component:()=>import('@/view/second')
}
需要注意的是:
params是路由的一部分,必须要在路由后面添加参数名。query是拼接在url后面的参数,没有也没关系。
params一旦设置在路由,params就是路由的一部分,如果这个路由有params传参,但是在跳转的时候没有传这个参数,会导致跳转失败或者页面会没有内容。
如果路由后面没有 /:id/:name,地址栏没有参数 例如:localhost:8080/#/second
但是如果你刷新一下,就会发现页面失败
因此我们不可能让用户不要刷新,所以我们必须在路由后面加上 /:id/:name
总结
1、传参可以使用params和query两种方式。
2、使用params传参只能用name来引入路由,即push里面只能是name:’xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!。
3、使用query传参使用path来引入路由。
4、params是路由的一部分,必须要在路由后面添加参数名。query是拼接在url后面的参数,没有也没关系。
5、二者还有点区别,直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示。