路由配置index.js文件:vue
import Vue from 'vue'; import Router from 'vue-router' import HelloWorld from "../components/HelloWorld"; import MyPage from "../components/MyPage"; import MyInfo from "../components/MyInfo"; Vue.use(Router) export default new Router({ routes: [ {path: '/',component: HelloWorld}, {path: '/my/:id?/:name?',component: MyPage,name: 'my', children:[ {path: 'info',name:'info',component: MyInfo} ] } ] })
注意: 須要傳參的路徑後,多個參數之間使用 / 分隔,如:path: '/my/:id?/:name?',可解決params 傳參刷新頁面參數丟失(異常)問題vue-router
<router-link :to="{name:'my',params: {id: myId,name: myName}}">我的中心</router-link>
<!-- name: , params: 獲取參數使用 $route.params.**-->this
<router-link :to="{path:'/my',params: {id: myId,name: myName}}">我的中心</router-link>
<!-- path: '/**', params: 不可用,獲取不到參數-->code
<router-link :to="{name:'my',query: {id: myId,name: myName}}">我的中心</router-link>
<!-- name: , query: 獲取參數使用 $route.query.**-->component
<router-link :to="{path:'/my',query: {id: myId,name: myName}}">我的中心</router-link>
<!-- path: '/' , query: 獲取參數使用 $route.query.-->router
總結:param傳參與query傳參不一樣路由
1.params傳參時只能用name來指定路由的跳轉,若用path:'/my',params 會被忽略,獲取到的參數爲undefined
2.獲取參數使用:this.$route.params.**
3.params傳入多個參數,刷新頁面,參數會出現異常,參數之間使用 / 分隔 可解決問題
4.params傳參地址欄路徑:http://localhost:8080/#/my/123/jack,參數間使用/分隔,不顯示參數的字段名(變量名),只顯示值get
5.query傳參,name和path都可使用,
6.獲取參數使用:this.$route.query.**
7.query傳入多個參數,刷新頁面,參數正常,參數格式?id=123&name=jack
8.query傳參地址欄路徑:http://localhost:8080/#/my?id=123&name=jack,參數以?開頭,使用&拼接分隔,字段名與值均顯示import
補充:!若使用 to='/my/123/jack' 傳參,默認使用params接收參數
!params傳參,若是沒有在路由中聲明參數,那麼參數不會在地址欄出現
!最好使用name來定義路由跳轉地址,傳入的參數最好與定義路由時的參數對應起來。
!定義路由時,是否指定參數、參數格式、是否(可選)帶? 等,搭配不一樣的傳參方式,name、path、params、query等都會形成不一樣的結果或異常,具體狀況具體分析解決。變量