vue路由傳參方式的方式總結(jié)及獲取參數(shù)詳解
一、聲明式傳參
1.params傳參(顯示參數(shù))
在url中會顯示出傳參的值,刷新頁面不會失去拿到的參數(shù),使用該方式傳值的時候,需要子路由提前配置好參數(shù):
//路由參數(shù)配置 const router = new VueRouter({ routes: [{ path: '/about/:id', component: User }] }) //聲明式導(dǎo)航使用 <router-link to="/about/12">跳轉(zhuǎn)</router-link>
//路由參數(shù)配置 const router = new VueRouter({ routes: [{ name: 'user1', path: '/about/:id', component: User }] }) //聲明式導(dǎo)航使用 <router-link :to="{ name: 'user1', params: { id: 123 } }">跳轉(zhuǎn)</router-link>
2.params傳參(不顯示參數(shù))
在url中不會顯示出傳參的值,但刷新頁面會失去拿到的參數(shù),使用該方式 傳值 的時候,需要子路由提前配置好name參數(shù):
//路由參數(shù)配置 const router = new VueRouter({ routes: [{ name: 'user1', path: '/about', component: User }] }) //聲明式導(dǎo)航使用 <router-link :to="{ name: 'user1', params: { id: 123 } }">跳轉(zhuǎn)</router-link>
3.query 傳參
query 傳過去的參數(shù)會拼接在地址欄中(?name=xx),刷新頁面數(shù)據(jù)不會丟失,使用path和name都可以:
//路由參數(shù)配置 const router = new VueRouter({ routes: [{ name: 'user1', path: '/about', component: User }] }) //使用name <router-link :to="{ name: 'user1', query: { id: 123 }}"></router-link> //使用path <router-link :to="{ path: '/about', query: { id: 123 } }"></router-link>
二、編程式傳參
1.params傳參(顯示參數(shù))
//路由配置 { path: '/child/:id', component: Child } //編程式使用 this.$router.push({ path:'/child/${id}', })
//路由配置 { path: '/child:id', component: Child, name:Child } //編程式使用 this.$router.push({ name:'Child', params:{ id:123 } })
2.params傳參(不顯示參數(shù))
//路由配置 { path: '/child', component: Child, name:Child } //編程式使用 this.$router.push({ name:'Child', params:{ id:123 } })
3.query 傳參
//路由配置 { path: '/child', component: Child, name:Child } //編程式使用 //name方式 this.$router.push({ name:'Child', query:{ id:1 } }) //path方式 this.$router.push({ path:'/child', query:{ id:1 } })
三、獲取參數(shù)
1、params的獲取方式
this.$route.params.xxx
2、query的獲取方式
this.$route.query.xxx
四、需要注意的點
1、如果使用params傳參,且參數(shù)是以對象的形式,跳轉(zhuǎn)路徑只能使用name形式而不能用path.
2、如果想要params參數(shù)想傳參也可以不傳參需要在占位符后面加?。
//路由參數(shù)配置 const router = new VueRouter({ routes: [{ path: '/search/:keyword?', name: 'search', component: () => import('@/pages/Search'), meta: { show: true } }] }) //編程式傳參 this.$router.push({ name: "search", params: {}, query: { keyword: this.keyword }, });
3、解決params傳值為空字符串路徑會出現(xiàn)問題:
this.$router.push({ name: "search", params: { keyword: "" || undefined }, query: { keyword: this.keyword }, });
總結(jié)
到此這篇關(guān)于vue路由傳參方式的方式總結(jié)及獲取參數(shù)的文章就介紹到這了,更多相關(guān)vue路由傳參及獲取參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue頁面中使用getElementsByClassName無法獲取元素的解決
這篇文章主要介紹了vue頁面中使用getElementsByClassName無法獲取元素的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03