通過Vue路由傳參的兩種方式及Vue組件中接收參數的方式


1. Vue傳參方式

1.1 通過動態路由傳參

我們經常需要把某種模式匹配到的所有路由,全都映射到同個組件。例如,我們有一個 User 組件,對於所有 ID 各不相同的用戶,都要使用這個組件來渲染。那么,我們可以在 vue-router 的路由路徑中使用“動態路徑參數”(dynamic segment) 來達到這個效果:

1
2
3
4
5
6
7
8
9
10
const User = {
template: '<div>User</div>'
}

const router = new VueRouter({
routes: [
// 動態路徑參數 以冒號開頭
{ path: '/user/:id', component: User }
]
})

在這個實例中,我們就可以通過:id這種方式實現把參數的值傳遞到組件中,現在呢,像 /user/foo 和 /user/bar這樣的路由,將把參數值foo、bar通過參數名id傳遞。

1.2 通過路由URL中添加query參數傳參

通過路由URL中添加query參數的方式,就和普通的http URL的get傳參方式一樣,通過在鏈接地址后面添加?queryName=queryValue的方式實現傳參,如:

1
2
3
4
5
6
7
8
9
10
const User = {
template: '<div>User</div>'
}

const router = new VueRouter({
routes: [
// 動態路徑參數 以冒號開頭
{ path: '/user/:id', component: User }
]
})

2. 組件中接收參數的方式

通過路由將參數傳遞后,我們需要在組件中進行接收,這樣才可以在需要用到此參數的地方拿到對應的參數值,對應着兩種傳參方式,也分別有兩種接收參數的形式。

2.1 通過this.$router.params接收

形如/user/:id這種的動態路由參數,我們可以通過this.$router.params接收,如在路由/user/:id中,在組件中拿到id的值的代碼如下:

1
var id = this.$route.params.id;

2.2 通過this.$router.query接收

形如/search?q=vue這種的通過在鏈接地址后面添加?queryName=queryValue的方式實現傳參的方式,我們可以通過this.$router.query接收,如在/search?q=vue中,在組件中拿到q的值的代碼如下:

1
var q = this.$route.query.q;

2.3 將路由中的參數設置到組件的props上

上面兩種接收參數的方式,都是通過$route對象來獲取參數值的,然而在組件中使用 $route 會使之與其對應路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
因此,我們可以使用 props 將組件和路由解耦,用這種方式取代直接在組件中使用 $route 獲取參數值的方式,代碼示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },

// 對於包含命名視圖的路由,你必須分別為每個命名視圖添加 `props` 選項:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})

這樣你便可以在任何地方使用該組件,使得該組件更易於重用和測試。

這里需要注意的是,props設置有三種模式

  • 布爾模式
    如果 props 被設置為 true,route.params 將會被設置為組件屬性。

    1
    2
    3
    4
    5
    const router = new VueRouter({
    routes: [
    { path: '/user/:id', component: User, props: true }
    ]
    })
  • 對象模式
    如果 props 是一個對象,它會被按原樣設置為組件屬性。當 props 是靜態的時候有用。

    1
    2
    3
    4
    5
    const router = new VueRouter({
    routes: [
    { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
    ]
    })
  • 函數模式
    你可以創建一個函數返回 props。這樣你便可以將參數轉換成另一種類型,將靜態值與基於路由的值結合等等。

    1
    2
    3
    4
    5
    const router = new VueRouter({
    routes: [
    { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
    ]
    })

URL /search?q=vue 會將 {query: ‘vue’} 作為屬性傳遞給 SearchUser 組件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM