3

$router和$route的区别,路由跳转方式name 、 path 和传参方式params 、query的区别

 2 years ago
source link: https://segmentfault.com/a/1190000040749751
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

$router和$route的区别,路由跳转方式name 、 path 和传参方式params 、query的区别

发布于 35 分钟前

一、$router和$route的区别
$router : 是路由操作对象,只写对象
$route : 路由信息对象,只读对象

//$router操作 路由跳转

// 字符串
   this.$router.push('home')
// 对象
   this.$router.push({ path: 'home' })
// 命名的路由
   this.$router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=123
   this.$router.push({ path: 'register', query: { plan: '123' }})

//$route读取 路由参数接收
var name = this.$route.params.name;

二、params 、query的区别

1.this.$route.query的使用

A、传参数:

this.$router.push({
         path: '/monitor',
         query:{
               id:id,
          }
})

B、获取参数:
this.$route.query.id
C、在url中形式(url中带参数)

http://172.19.186.224:8080/#/monitor?id=1

D、页面之间用路由跳转传参时,刷新跳转后传参的页面,数据还会显示存在(项目中遇到此问题)

2.this.$route.params的使用
A、传参数:

this.$router.push({
         name: 'monitor',
         params:{
               id:id,
          }
})

B、获取参数:
this.$route.params.id
C、在url中形式(url中不带参数)
http://172.19.186.224:8080/#/monitor
D、页面之间用路由跳转传参时,刷新跳转后传参的页面,数据不存在(项目中遇到此问题)

三、name 、 path的区别

path 和 Name路由跳转方式,都可以用query传参
path路由跳转方式,params传参会被忽略,只能用name命名的方式跳转
params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
另外,二者还有点区别,直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示

注意:params传参如果路由上面不写参数,也是可以传过去的,但不会在url上面显示出你的参数,并且当你跳到别的页面或者刷新页面的时候参数会丢失,要怎么解决?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK