vue 如何将参数放到连接上_通过Vue路由传参的两种方式及Vue组件中接收参数的方式...
1. Vue傳參方式
1.1 通過動態(tài)路由傳參
我們經(jīng)常需要把某種模式匹配到的所有路由,全都映射到同個(gè)組件。例如,我們有一個(gè) User 組件,對于所有 ID 各不相同的用戶,都要使用這個(gè)組件來渲染。那么,我們可以在 vue-router 的路由路徑中使用“動態(tài)路徑參數(shù)”(dynamic segment) 來達(dá)到這個(gè)效果:
1
2
3
4
5
6
7
8
9
10
const User = {
template: '
User'}
const router = new VueRouter({
routes: [
// 動態(tài)路徑參數(shù) 以冒號開頭
{ path: '/user/:id', component: User }
]
})
在這個(gè)實(shí)例中,我們就可以通過:id這種方式實(shí)現(xiàn)把參數(shù)的值傳遞到組件中,現(xiàn)在呢,像 /user/foo 和 /user/bar這樣的路由,將把參數(shù)值foo、bar通過參數(shù)名id傳遞。
1.2 通過路由URL中添加query參數(shù)傳參
通過路由URL中添加query參數(shù)的方式,就和普通的http URL的get傳參方式一樣,通過在鏈接地址后面添加?queryName=queryValue的方式實(shí)現(xiàn)傳參,如:
1
2
3
4
5
6
7
8
9
10
const User = {
template: '
User'}
const router = new VueRouter({
routes: [
// 動態(tài)路徑參數(shù) 以冒號開頭
{ path: '/user/:id', component: User }
]
})
2. 組件中接收參數(shù)的方式
通過路由將參數(shù)傳遞后,我們需要在組件中進(jìn)行接收,這樣才可以在需要用到此參數(shù)的地方拿到對應(yīng)的參數(shù)值,對應(yīng)著兩種傳參方式,也分別有兩種接收參數(shù)的形式。
2.1 通過this.$router.params接收
形如/user/:id這種的動態(tài)路由參數(shù),我們可以通過this.$router.params接收,如在路由/user/:id中,在組件中拿到id的值的代碼如下:
1
var id = this.$route.params.id;
2.2 通過this.$router.query接收
形如/search?q=vue這種的通過在鏈接地址后面添加?queryName=queryValue的方式實(shí)現(xiàn)傳參的方式,我們可以通過this.$router.query接收,如在/search?q=vue中,在組件中拿到q的值的代碼如下:
1
var q = this.$route.query.q;
2.3 將路由中的參數(shù)設(shè)置到組件的props上
上面兩種接收參數(shù)的方式,都是通過$route對象來獲取參數(shù)值的,然而在組件中使用 $route 會使之與其對應(yīng)路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
因此,我們可以使用 props 將組件和路由解耦,用這種方式取代直接在組件中使用 $route 獲取參數(shù)值的方式,代碼示例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const User = {
props: ['id'],
template: '
User {{ id }}'}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 對于包含命名視圖的路由,你必須分別為每個(gè)命名視圖添加 `props` 選項(xiàng):
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
這樣你便可以在任何地方使用該組件,使得該組件更易于重用和測試。
這里需要注意的是,props設(shè)置有三種模式
布爾模式
如果 props 被設(shè)置為 true,route.params 將會被設(shè)置為組件屬性。
1
2
3
4
5
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true }
]
})
對象模式
如果 props 是一個(gè)對象,它會被按原樣設(shè)置為組件屬性。當(dāng) props 是靜態(tài)的時(shí)候有用。
1
2
3
4
5
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
]
})
函數(shù)模式
你可以創(chuàng)建一個(gè)函數(shù)返回 props。這樣你便可以將參數(shù)轉(zhuǎn)換成另一種類型,將靜態(tài)值與基于路由的值結(jié)合等等。
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 組件。
總結(jié)
以上是生活随笔為你收集整理的vue 如何将参数放到连接上_通过Vue路由传参的两种方式及Vue组件中接收参数的方式...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天猫投影仪模糊怎么办(汉典天字的基本解释
- 下一篇: 刺激战场春节模式什么意思(如何刺激女人让