路由插件
npm i vue-router
路由插件的使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter); // Vue.use(插件) 在Vue中安裝插件
const router = new VueRouter({
// 路由配置
})
new Vue({
...,
router
})
1.基本使用
// 路由配置
const router = new VueRouter({
routes: [ // 路由規則
// 當匹配到路徑 /foo 時,渲染 Foo 組件
{ path: '/foo', component: Foo },
// 當匹配到路徑 /bar 時,渲染 Bar 組件
{ path: '/bar', component: Bar }
]
})
<!-- App.vue -->
<div class="container">
<div>
<!-- 公共區域 -->
</div>
<div>
<!-- 頁面區域 -->
<!-- vue-router 匹配到的組件會渲染到這里 -->
<RouterView />
</div>
</div>
2.路由模式
路由模式決定了:
- 路由從哪里獲取訪問路徑
- 路由如何改變訪問路徑
vue-router提供了三種路由模式:
-
hash:默認值,路由從瀏覽器地址欄中的hash部分獲取路徑,改變路徑也是改變的hash部分,該模式兼容性最好,
http://localhost:8081/#/blog --> /blog http://localhost:8081/about#/blog --> /blog -
history:路由從瀏覽器地址欄的
location.pathname中獲取路徑,改變路徑使用的H5的history api,該模式可以讓地址欄最友好,但是需要瀏覽器支持history apihttp://localhost:8081/#/blog --> / http://localhost:8081/about#/blog --> /about http://localhost:8081/blog --> /blog -
abstract:路由從記憶體中獲取路徑,改變路徑也只是改動記憶體中的值,這種模式通常應用到非瀏覽器環境中,
記憶體: / --> / 記憶體: /about --> /about 記憶體: /blog --> /blog
3.導航
vue-router提供了全域的組件RouterLink,它的渲染結果是一個a元素
<RouterLink to="/blog">文章</RouterLink>
<!-- mode:hash 生成 -->
<a href="#/blog">文章</a>
<!-- mode:history 生成 -->
<!-- 為了避免重繪頁面,vue-router實際上為它添加了點擊事件,并阻止了默認行為,在事件內部使用hitory api更改路徑 -->
<a href="/blog">文章</a>

激活狀態
默認情況下,vue-router會用 當前路徑 匹配 導航路徑 :
- 如果當前路徑是以導航路徑開頭,則算作匹配,會為導航的a元素添加類名
router-link-active - 如果當前路徑完全等于導航路徑,則算作精確匹配,會為導航的a元素添加類名
router-link-exact-active
例如,當前訪問的路徑是/blog,則:
| 導航路徑 | 類名 |
|---|---|
| / | router-link-active |
| /blog | router-link-active router-link-exact-active |
| /about | 無 |
| /message | 無 |
可以為組件RouterLink添加bool屬性exact,將匹配規則改為:必須要精確匹配才能添加匹配類名router-link-active
例如,當前訪問的路徑是/blog,則:
| 導航路徑 | exact | 類名 |
|---|---|---|
| / | true | 無 |
| /blog | false | router-link-active router-link-exact-active |
| /about | true | 無 |
| /message | true | 無 |
例如,當前訪問的路徑是/blog/detail/123,則:
| 導航路徑 | exact | 類名 |
|---|---|---|
| / | true | 無 |
| /blog | false | router-link-active |
| /about | true | 無 |
| /message | true | 無 |
另外,可以通過active-class屬性更改匹配的類名,通過exact-active-class更改精確匹配的類名
4.命名路由
使用命名路由可以解除系統與路徑之間的耦合
// 路由配置
const router = new VueRouter({
routes: [ // 路由規則
// 當匹配到路徑 /foo 時,渲染 Foo 組件
{ name:"foo", path: '/foo', component: Foo },
// 當匹配到路徑 /bar 時,渲染 Bar 組件
{ name:"bar", path: '/bar', component: Bar }
]
})
<!-- 向to屬性傳遞路由資訊物件 RouterLink會根據你傳遞的資訊以及路由配置生成對應的路徑 -->
<RouterLink :to="{ name:'foo' }">go to foo</RouterLink>
已禁用此檔案中的部分內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/273352.html
標籤:其他
