vue-router傳遞參數分為兩大類
- 編程式的導航 router.push
- 聲明式的導航<router-link>
編程式的導航router.push
傳遞參數分為兩種類型:字符串,對象
字符串
字符串的方式是直接將路由地址以字符串的方式來跳轉,這種方式簡單但不能傳遞參數
this.$router.push("home");
對象
想要傳遞參數主要就是以對象的方式來寫,分為兩種方式:命名路由,查詢參數
1.命名路由
命名路由的前提是在注冊路由的地方給路由命名如:
命名路由傳遞參數需要使用params來傳遞,這里一定要注意使用params不是query。目標頁面接收傳遞參數也要使用params
方法如下:
this.$router.push({ name: 'news', params: { userId: 123 }})
接收傳遞參數:
<template> <div> this is the news page.the transform param is {{this.$route.params.userId}} </div> </template>
2.查詢參數
查詢參數就是在路由地址后面帶上參數,和傳統的url參數一致的,傳遞參數使用query而且必須配合path來傳遞參數而不能使用name,目標頁面接收傳遞參數使用query
使用方法如下:
this.$router.push({ path: '/news', query: { userId: 123 }});
接收參數如下:
<template> <div> this is the news page.the transform param is {{this.$route.query.userId}} </div> </template> <script> </script>
聲明式的導航
聲明式的導航和編程式的一樣
字符串
<router-link to="news">click to news page</router-link>
對象
1.命名路由
<router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link>
2.查詢參數
<router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link>