前沿
最近,由于工作需要,需要去面試一些前端,由于自己是那種實操型的程序猿,不擅長這方面,但是沒辦法,只能硬著頭皮上,第一次有些緊張,后來慢慢就好了,在過程中,發(fā)現(xiàn)面試別人自己可以系統(tǒng)的學(xué)到很多知識,比如說有些原理性的東西,系統(tǒng)的知識,就可以在學(xué)習(xí)一遍,并且比之前理解的更透徹了,所以說,什么時候都可以學(xué)習(xí),加油吧,騷年。
下面主要說一下vue $router 路由傳參的3種方法詳解,里邊包括了一些,配置,傳參,接參的方法,來吧,上代碼
第一種:使用router的name屬性也就是params來傳遞參數(shù)
這個方法有一個bug就是當(dāng)你傳參過去的時候,再次刷新頁面時參數(shù)就會丟失。解決方法下邊會說到。
step:1,首先需要在router/index.js里邊配置每個頁面的路徑,name屬性,看例子:
import Vue from 'vue'
import Router from 'vue-router'
const _import = require('./_import_' + process.env.NODE_ENV)
Vue.use(Router)
export const constantRouterMap = [{
path: '/login/:userId/:id',
name:'Message', //就是要在路由配置里邊配置這個屬性,用來知道你要跳轉(zhuǎn)到那個頁面的名字
/***
* 如果想做到頁面刷新,參數(shù)不丟失,就必須在path后面加上這個參數(shù)
* 但是這樣做的話就會導(dǎo)致參數(shù)顯示在url的后面,(在這一點上)跟query沒什么區(qū)別了。
* 多個參數(shù)也可以一直往后邊追加
*/
component: _import('login/index'),
hidden: true
},
{
path: '',
component: Layout,
redirect: 'dashboard',
icon: 'dashboard',
hidden: true,
noDropDown: true,
children: [{
path: 'dashboard',
name: '首頁',
component: _import('main/index'),
meta: {
title: 'dashboard',
icon: 'dashboard',
noCache: true
}
}]
}
]
export default new Router({
routes: constantRouterMap
})
step:2,在傳值頁面的寫法:
//用這種方法傳參,必須這么些,不能寫path,否則你在取參數(shù)的時候this.$router.params.userId就是undefined.這是因為,params只能用name來引入路由,
this.$router.push({
name:"'Message'",//這個name就是你剛剛配置在router里邊的name
params:{
userId:"10011"
}
})
step:3,在取值頁面的寫法:
切記,再取參數(shù)的時候一定是this.
router,切記。
this.$route.params.userId
第二種:使用query來傳遞參數(shù)
step:1,在傳值頁面的寫法:
this.$router.push({
path:"/login",//這個path就是你在router/index.js里邊配置的路徑
query:{
userId:"10011"
}
})
step:2,在取值頁面的寫法:
第一種:
this.$router.currentRoute.query.userId
第二種:
這種方法再取參數(shù)的時候一定是this.$route 不是 this.$router,切記。
this.$route.query.userId
第三種:使用vue里的<router-link>標(biāo)簽來傳遞參數(shù)
step:1,在傳值頁面的寫法:
<router-link target="_blank"
:to="{path:'/login',query:{userId: "33333"}}">
</router-link>
step:2,在取值頁面的寫法:同第二種。
其實,router-link也可以使用name的方法傳參
同樣,這種方法也需要在router/index.js里邊配置每個頁面的路徑,name屬性
name:'Message', //就是要在路由配置里邊配置這個屬性,用來知道你要跳轉(zhuǎn)到那個頁面的名字
<router-link :to="{name:''Message'',params:{userId:'1234'}}">Hi頁面1</router-link>
取參方法:
this.$route.params.userId
總結(jié)
真的是學(xué)無止境,好多時候還是要注意好多細(xì)節(jié)的東西,否則學(xué)到的就只是皮毛。以上為我項目過程中遇到的坑以及總結(jié)的經(jīng)驗,若有什么錯誤的地方,還請伙伴們多多指正。