-
<view-router>實際上是對瀏覽器window.history的一個封裝
如:當前路徑是http://localhost:8090/goods/image,在瀏覽器控制臺執(zhí)行history.pushState("desc","title","/cart")路徑將跳轉(zhuǎn)至http://localhost:8090/cart。 -
<router-link to="/goods/image">則是對a標簽的封裝,to中需要傳遞完整的字符串路徑。 -
this.$route能拿到當前路由的相關(guān)信息
1.動態(tài)路由
“路徑參數(shù)”使用冒號 : 標記, 如/goods/:goodsId/user/:goodsName。當匹配到一個路由時,參數(shù)值會被設(shè)置到 this.$route.params。
<body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id=app>
<router-link to="/goods/89/user/candy">link1</router-link>
<router-link to="/goods/90/user/hank">link2</router-link>
<router-view></router-view>
</div>
<script>
// GoodsList 中通過$route.params拿到參數(shù)
const GoodsList = { template:
`
<div>
<p>goodsId: {{$route.params.goodsId}}</p>
<p>goodsName:{{$route.params.goodsName}}</p>
</div>
`}
const routes = [{
path:'/goods/:goodsId/user/:goodsName', // goodsId和goodsName是路由的參數(shù)而非頁面跳轉(zhuǎn)的參數(shù)
name: 'GoodsList',
component: GoodsList
}]
const router = new VueRouter({
routes
})
const app = new Vue({
router,
// $route 表示當前路由
watch:{
$route(val,old){
console.log(val)
}
}
}).$mount('#app')
</script>
</body>

動態(tài)路由.png
2.嵌套路由
嵌套路由使用children
const routes = [
{
path:'/goods',
name: 'GoodsList',
component: GoodsList,
children:[
{
path:'title', // 二級路由,注意這里不能寫'/title','/title'是一級路由
name:'title',
component:Title
},
{
path:'image',
name:'image',
component:Image
},
]
},
{
path:'/cart', //一級路由
name:'cart',
component:Cart
}]
GoodsList 中的<router-view>是裝二級路由的容器
const GoodsList = { template: `
<div>
商品列表頁面
<br>
<router-link to="/goods/title">顯示商品標題</router-link>
<router-link to="/goods/image">顯示商品圖片</router-link>
<router-link to="/cart">顯示購物車</router-link>
<router-view></router-view>
</div>
`}

嵌套路由.png
3.編程式路由
this.$router.push方法可接收路徑字符串,也可接收對象,也可接收帶參數(shù)的對象,接收帶參數(shù)的對象時,傳遞的參數(shù)可在目標路由頁面中通過$route.query來獲取
// js
this.$router.push({path:'/cart?cartId=123'})
// html
<div>購物車:{{$route.query.cartId}}</div>
4.命名路由和命名視圖
有時候想同時 (同級) 展示多個視圖,而不是嵌套展示,這時候就需要用到命名路由和命名視圖。
<div id="app">
<router-view></router-view> <!--用于顯示默認視圖-->
<router-view name="title2"></router-view>
<router-view name="title3"></router-view>
</div>
命名路由的方式需要傳遞一個對象,使用v-bind:
const Title1 = { template: `
<div>
<router-link v-bind:to='{name:"cart",params:{cartId:123}}'>title1</router-link>
</div>
` };
const routes = [{
path: "/",
components: {
default: Title1, // 默認視圖
title2: Title2,
title3: Title3
}
},{
path:'/cart/:cartId',
name:'cart',
component:Cart,
}];
如下圖所示,Title1,Title2, Title3三個視圖同時顯示:

命名路由和命名視圖.png