router-link
// 注意:router-link中鏈接如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當(dāng)前路由開始携悯。
<router-link :to="{name:'home'}">
<router-link :to="{path:'/home'}"> //name,path都行, 建議用name
//獲取參數(shù)的方法和下面push()一樣
<router-link :to="{name:'home', params: {id:1}}">
<router-link :to="{name:'home', query: {id:1}}">
this.$router.push()
params傳參
路由配置 path: "/home/:id"
或者path: "/home:id"
方椎,不然刷新頁面會取不到id(undefined)
this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name
//html 取參
$route.params.id
// script 取參
this.$route.params.id
query傳參
this.$router.push({name:'home',query: {id:'1'}}) //name
this.$router.push({path:'/home',query: {id:'1'}}) //path
// html 取參
$route.query.id
// script 取參
this.$route.query.id
總結(jié)
query類似 get, 跳轉(zhuǎn)之后頁面 url后面會拼接參數(shù),類似?id=1, 非重要性的可以這樣傳, 密碼之類還是用params
params類似 post, 跳轉(zhuǎn)之后頁面 url后面不會拼接參數(shù) , 但是刷新頁面id 會消失
this.$router.replace() this.$router.go(n)
this.$router.push
跳轉(zhuǎn)到指定url路徑钦睡,并想history棧中添加一個(gè)記錄,點(diǎn)擊后退會返回到上一個(gè)頁面
this.$router.replace
跳轉(zhuǎn)到指定url路徑膀估,但是history棧中不會有記錄幔亥,點(diǎn)擊返回會跳轉(zhuǎn)到上上個(gè)頁面 (就是直接替換了當(dāng)前頁面)
this.$router.go(n)
向前或者向后跳轉(zhuǎn)n個(gè)頁面,n可為正整數(shù)或負(fù)整數(shù)
懶加載
const aRounter = ()=>import('@/components/routerCom/aRouter')
導(dǎo)航守衛(wèi)
//路由獨(dú)享的守衛(wèi)
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
//路由全局守衛(wèi)
const router = new Router({.......})
//每次訪問路由前察纯,通過vuex中的actions中的異步方法確認(rèn)是否登錄狀態(tài)
router.beforeEach((to,from,next)=>{
if(to.name != 'login' && to.name != 'index'){
store.dispatch('me/checkMe')
}
next()
})
actions:{
async checkMe({commit}){
//請求/me接口,對登錄信息進(jìn)行判斷,并保留狀態(tài)
const result = await Vue.prototype.$axiosGet('/me',{});
if(!result){
router.push({name:'login'})
return
}
commit('changeLogin',{result})
}
}
補(bǔ)充
1.路由概念 2.動態(tài)路由 http://www.reibang.com/p/a7484d9c43f0