vue router
vue-router 就是封裝 瀏覽器中history。
使用vue-router用來構建SPA
<router-link to='/'></router-link> 或者 this.$router.push({path: '/'}) 相當於 <a></a>
<router-view></router-view> 主鍵的渲染
動態路由
模式 | 匹配路徑 | $router.params |
---|---|---|
/usr/:username | /usr/xx | { username: 'xx'} |
hash & history
- hash 默認模式,路由中展現爲 url/#/, 後面的url取hash
- history : mode 設置爲history 後,就和平時使用的url一樣
export default new Router({
mode: 'history',
routers : [{
path: '/',
name: main,
component:Main
}
]
})
嵌套路由
export default new Router({
mode: 'history',
routers : [{
path: '/',
name: main,
component:Main,
children: [
{
path: 'title',
name: title,
component:Title,
}
]
}
]
})
在Main組件中也要加<router-view>
編程路由
this.$router.push('name')
this.$router.push({path:'name'})
this.$router.push({path:'name?id=123'})
this.$router.push({path:'name', query: {a: 123}})
命名路由
使用name 進行 路由跳轉, v-bind:to='{name: 'xx'}', xx爲路由定義的name值
<router-link :to='{name: 'cart'}'></router-link>
<router-link :to='{name: 'cart', params:{id: 123}}'></router-link>
命名視圖
加載多個視圖, 一般用不到
export default new Router({
mode: 'history',
routers : [{
path: '/',
name: main,
component: {
default: List,
title: Title,
img: Img
}
}
]
})
<router-view name='title'></router-view>
<router-view name='img'></router-view>