前面說到了路由配置 vue小項目總結與筆記【二】——vue的單文件組件模板和路由,但其路由導航功能是不能傳遞參數的,是靜態路由。
靜態路由:
routes: [{ path: '/', name: 'Home', component: Home }]
而能傳遞參數的路由模式,由於可以傳遞參數,所以其對應的路由數量是不確定的,故稱之為 動態路由。那么動態路由如何傳遞參數?
在參數名前面加上 : ,然后將參數寫在路由的 path 內.如下:
routes: [{ path: '/', name: 'Home', component: Home }, { path: '/city', name: 'City', component: City }, { // 動態路由參數 :id
path: '/detail/:id', name: 'Detail', component: Detail }]
這樣定義之后,vue-router就會匹配到所有的
/detail/1, /detail/2, /datail/3......
在<router-link>
我們加入一個 params
屬性來指定具體的參數值
<li>
<router-link :to ="{params :{id:1}}" >
<div>首頁</div>
</router-link>
</li>
這時候對應的網址是http://localhost:8080/detail/1。
如何把參數讀取出來?
路由參數是被設置到 this.$route.params 中的,想取到這個值,用 this.$route.params.id 就可以了。
例如我想根據點擊的景點名,進入對應的景點詳情中,
getDetailInfo () { // 相當於 /api/detail.json?id=this.$route.params.id' axios.get('/api/detail.json', { params: { id: this.$route.params.id } }).then(this.handleGetDataSucc) }
利用這個取到的id值,去篩選ajax獲取到的data數據,就可以實現數據對應了。即:點擊第一個,跳轉到鏈接/detail/1,數據也是第一條……