Vue-Router
1. 什么是前端路由
- 網(wǎng)址:router.vuejs.org
- 后端渲染\后端路由
- 前后端分離
- SPA\前端路由
2. 路由的基本配置
- 配置路由信息(index.js)
- 安裝 vue-router
npm install vue-router
- vue.use => 創(chuàng)建對象 => 掛載到實例上
import VueRouter from "vue-router"
import Vue from "vue"
// 1. 通過vue.use(插件)底循,安裝插件
Vue.use(VueRouter)
// 2. 創(chuàng)建對象
const router = new VueRouter({
// 配置路由和組件之間的關(guān)系(默認(rèn)為 hash 值,可通過mode 改成 history 模式)
routes,
})
// 3. 掛載到實例上(配置每個映射關(guān)系)
// 引入兩個組件(動態(tài)導(dǎo)入) <== 路由懶加載
const Home = () => import("../components/Home")
const User = () => import("../components/User")
const routes = [
{
// 默認(rèn)路徑
path: "",
redirect: "/home", // redirect 重定向
},
{
path: "/home",
component: Home,
},
{
path: "/user/:id",
component: User,
},
]
<template>
<div id="app">
<router-link to="/home" tag="button">
首頁
</router-link>
// replace 改變跳轉(zhuǎn)方式征讲,不能返回上一頁
<router-link v-bind:to="'/user/' + useId" replace>
用戶
</router-link>
<router-view></router-view>
</div>
</template>
3. 細(xì)節(jié)處理
- 默認(rèn)路由:redirect
- mode: "history"
修改為 history 模式(網(wǎng)址中不存在 /# )
- router-link => tag/replace/active-class
tag: 定義渲染后的標(biāo)簽
replace: 改變跳轉(zhuǎn)方式腕铸,不能訪問上一頁
active-class: 改變活躍標(biāo)簽的類名
route 的比較
注意:所有的組件都繼承著 Vue 的原型
- $router
- router 是路由棧
- $route
- route 是當(dāng)前活躍節(jié)點
4. 動態(tài)路由
- /user/:id
- this.$route.params.id
5. 參數(shù)的傳遞
-
params(數(shù)據(jù)少的情況)
- 配置路由格式: /router/:id
- 傳遞的方式: 在 path 后面跟上對應(yīng)的值
- 傳遞后形成的路徑: /router/123,/router/abc
// 配置路由
{ path: '/user/:id', component: User },
// 傳遞參數(shù)
<router-link v-bind:to="'/user/' + useId" replace>
用戶
</router-link>
// 組件中傳入?yún)?shù)
<h2>{{$route.params.id}}</h2>
-
query -> URL(大量數(shù)據(jù))[3]
- URL:配置的方法: /router
- 傳遞的方式: 對象中使用 query 的 key 作為傳遞方式
- 傳遞后形成的路徑: /router?id=123, /router?id=abc
// 傳遞參數(shù)
<router-link v-bind:to="{path: '/profile',query: {name:'why',age='18'}}">
檔案
</router-link>
// 組件中傳入?yún)?shù)
<h2>{{$route.query.name}}</h2>
6. 路由嵌套
- children
7. 導(dǎo)航守衛(wèi)
- 全局導(dǎo)航守衛(wèi)
// 前置守衛(wèi)(guard)
router.beforeEach((to, from, next) => {
// 默認(rèn)重定向
document.title = to.matched[0].meta.title
next()
})
// 后置鉤子(hook)
router.afterEach((to, from) => {
console.log("hook")
})
- 路由獨享守衛(wèi)
- 組件類守衛(wèi)
8. keep-alive
- 基本使用
beforeRouteLeave(to,from,next){
this.path=this.$route.path
next()
}
- 兩個屬性
- include ==> 字符串或正則表達式盖桥,只有匹配的組件會被緩存
- exclude ==> 字符串或正則表達式除师,任何匹配的組件都不會被緩存
-
router-link 標(biāo)簽最終默認(rèn)被渲染成 a 標(biāo)簽(tag 可以修改成其他標(biāo)簽) ?
-
router-view 表示渲染的內(nèi)容出現(xiàn)的位置 ?
-
URL:
協(xié)議://主機端口/路徑凝化?查詢
scheme://host:port/path?query#fragment