vue2中vue-router引入使用詳解
1.介紹
Vue 很適合用來構(gòu)建單頁面應(yīng)用。對于大多數(shù)此類應(yīng)用,都推薦使用官方支持的Vue Router;在單頁面應(yīng)用(Single-page application)中,客戶端的 JavaScript 可以攔截頁面的跳轉(zhuǎn)請求,動態(tài)獲取新的數(shù)據(jù),然后在無需重新加載的情況下更新當(dāng)前頁面。這樣通??梢詭砀樆挠脩趔w驗,因為這類場景下用戶通常會在很長的一段時間中做出多次交互。這類的單頁面應(yīng)用中,路由的更新是在客戶端執(zhí)行的。
Vue Router 是 Vue 的官方路由。它與 Vue.js 核心深度集成,讓用 Vue.js 構(gòu)建單頁應(yīng)用變得輕而易舉。功能包括:
- 嵌套路由映射
- 動態(tài)路由選擇
- 模塊化、基于組件的路由配置
- 路由參數(shù)、查詢、通配符
- 展示由 Vue.js 的過渡系統(tǒng)提供的過渡效果
- 細(xì)致的導(dǎo)航控制
- 自動激活 CSS 類的鏈接
- HTML5 history 模式或 hash 模式
- 可定制的滾動行為
- URL 的正確編碼
我們來介紹Vue Router的基本使用。本文基于vue2以及vue-router@3.5.1編寫。
2.Vue Router的使用
2.1 安裝
對于vue2,我們推薦使用vue-router 3.x版本。若大于4.x,則部分功能無法在vue2中正常引入使用。
node環(huán)境安裝如下:
npm install vue-router@3.5.1
2.2 項目引入使用
在我們工程項目中,路由文件通常需要單獨管理,以便于后續(xù)的使用以及維護。再此基礎(chǔ)下,我們引入分為兩步:
- 創(chuàng)建統(tǒng)一管理路由入口文件
- vue項目引入使用路由入口文件
2.2.1 創(chuàng)建路由文件
在與main.ts文件的同級目錄下創(chuàng)建router文件夾,并添加index.ts文件(使用ts,若使用js也同理)。
文件內(nèi)容如下:
import Vue from "vue"; import VueRouter from "vue-router"; import routers from "./practice/practice"; import echartsRouters from './practice/echarts' // 注冊vue-router中的所有組件 Vue.use(VueRouter); const allRouter = [...routers, ...echartsRouters]; const router = new VueRouter({ mode: "history", routes: allRouter }); export default router;
Vue.use(VueRouter)是為了注冊所有組件,以方便全局使用,比如routerview等。
2.2.2 main.ts 引入
代碼如下:
import Vue from "vue"; import App from "./App.vue"; import "./registerServiceWorker"; import router from "./router"; import store from "./store"; Vue.config.productionTip = false; new Vue({ router, store, render: h => h(App) }).$mount("#app");
2.2.3 App.vue配置
<template> <div id="app"> <router-view></router-view> </div> </template> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
2.3 整體目錄結(jié)構(gòu)
├── public/ # 靜態(tài)資源目錄
├── src/
│ ├── assets/ # 全局資源目錄
│ │ ├── fonts/
│ │ └── images/
│ │
│ ├── components/ # 全局組件
│ │ └── UserSelectTable/
│ │ ├── style/
│ │ │ ├── _var.scss
│ │ │ └── index.scss
│ │ ├── UserSelectTable.vue
│ │ └── index.ts
│ │
│ ├── store/ # 狀態(tài)管理
│ │ ├── plugins/
│ │ │ ├── persist.ts
│ │ │ └── qiankun.ts
│ │ ├── modules/ # 除非業(yè)務(wù)過于復(fù)雜,否者不推薦
│ │ │ ├── cart.ts
│ │ │ └── products.ts
│ │ ├── getters.ts # 根級別的 getters
│ │ ├── actions.ts # 根級別的 action
│ │ ├── mutations.ts # 根級別的 mutation
│ │ └── index.ts
│ │
│ ├── router/
│ │ ├── routes.ts # 路由配置
│ │ └── index.ts
│ │
│ ├── views/ # 頁面級組件
│ │ ├── Home/
│ │ │ ├── components/ # 頁面級組件
│ │ │ ├── services/ # 頁面級組數(shù)據(jù)請求
│ │ │ │ └── repo.ts
│ │ │ └── Home.vue
│ │ │
│ │ └── About/
│ │ ├── components/
│ │ └── About.vue
│ │
│ └── main.ts # 應(yīng)用入口
│
├── .browserslistrc
├── .env
├── .editorconfig
├── .eslintrc.js
├── .prettierrc
├── babel.config.js
├── vue.config.js
├── jsconfig.json
└── package.json
2.4 使用方法
router引入之后,我們可以通過router自帶的組件來進行路由管理,以方便大型項目的路由訪問以及統(tǒng)一管理。以下介紹常用的幾種用法。
2.4.1 使用router-view進行頁面視圖切換
入之后我們單頁面應(yīng)用可以在app.vue配置使用router-view來切換頁面,并進行嵌套路由配置。引入之后,在 Vue 實例中,你可以通過 $router 訪問路由實例,若想要導(dǎo)航到不同的 URL,使用this.$router.push(...)進行跳轉(zhuǎn)。
嵌套路由案例如下:
{ path: '/user', component: User, children: [ { // 當(dāng)訪問 /user/profile 時, // 頁面組件UserProfile 會被渲染在 User 的 <router-view> 中 path: 'profile', component: UserProfile }, { // 當(dāng)訪問 /user/posts 時 // 頁面組件UserPosts 會被渲染在 User 的 <router-view> 中 path: 'posts', component: UserPosts } ] }
詳細(xì)的router-view使用方法可見vue router-view使用詳解
2.4.2 使用router-link進行頁面跳轉(zhuǎn)
當(dāng)使用 <router-link> 時,內(nèi)部會調(diào)用router.push(...)這個方法,所以點擊 <router-link :to="..."> 相當(dāng)于調(diào)用 router.push(...)
<router-link :to="{ name: 'user', params: { userId: '12345678' }}">User</router-link>
2.4.3 路由重定向
定義路由時添加redirect屬性,即可實現(xiàn)重定向,案例如下:
routes: [ { path: '/a', redirect: '/b' } ]
該案例為,訪問路由a時,會自動重定向到b。做廢棄頁面改造時通常會非常有用
2.4.4 路由傳參
在頁面跳轉(zhuǎn)時,可以在push方法中添加參數(shù),不同的路由訪問方式,傳參方式不同;
- 使用path跳轉(zhuǎn)時,路由傳參通過query方式;
- 使用name跳轉(zhuǎn)時,路由傳參通過params’方式;
這里的path和name都是我們路由文件對應(yīng)的鍵值;如下:
{ path: "/productList", name: "productList", component: () => import("@/views/productList/index.vue") },
使用path和name路由傳參代碼如下:
path路由傳參
// path跳轉(zhuǎn)對應(yīng)query方式傳參 this.$router.push({ path: '/routerJump', query: { name: 'sam', stuNo: '1234' } })
在下一個頁面取參:
// 使用query取參 this.stuNo = this.$route.query.stuNo;
name路由傳參
// // name跳轉(zhuǎn)對應(yīng)params方式傳參 this.$router.push({ name: 'routerJump', params: { name: 'sam', stuNo: '1234' } })
在下一個頁面取參:
// 使用params取參 this.stuNo = this.$route.params.stuNo;
注意,取參的時候使用的$route中的route是沒有“r”的。
2.4.5 路由守衛(wèi)
1、路由加載前置守衛(wèi):router.beforeEach
router.beforeEach((to, from, next) => { // ... })
每個守衛(wèi)方法接收三個參數(shù):
to: Route: 即將要進入的目標(biāo)路由
from: Route: 當(dāng)前導(dǎo)航正要離開的路由
next: Function: 一定要調(diào)用該方法來 resolve 這個鉤子。執(zhí)行效果依賴 next 方法的調(diào)用參數(shù)。
- next(): 進行管道中的下一個鉤子。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)。
- next(false): 中斷當(dāng)前的導(dǎo)航。如果瀏覽器的 URL 改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應(yīng)的地址。
- next('/') 或者 next({ path: '/' }): 跳轉(zhuǎn)到一個不同的地址。當(dāng)前的導(dǎo)航被中斷,然后進行一個新的導(dǎo)航。你可以向 next 傳遞任意位置對象,且允許設(shè)置諸如 replace: true、name: 'home' 之類的選項以及任何用在 router-link 的 to prop 或 router.push 中的選項。
- next(error): (2.4.0+) 如果傳入 next 的參數(shù)是一個 Error 實例,則導(dǎo)航會被終止且該錯誤會被傳遞給 router.onError() 注冊過的回調(diào)。
確保 next 函數(shù)在任何給定的導(dǎo)航守衛(wèi)中都被嚴(yán)格調(diào)用一次。它可以出現(xiàn)多于一次,但是只能在所有的邏輯路徑都不
重疊的情況下,否則鉤子永遠(yuǎn)都不會被解析或報錯。
使用案例:登錄認(rèn)證成功跳轉(zhuǎn),否則不跳轉(zhuǎn):
router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) else next() })
2、路由跳轉(zhuǎn)后置鉤子
對于后置鉤子和守衛(wèi)不同的是,這些鉤子不會接受 next 函數(shù)也不會改變導(dǎo)航本身:
router.afterEach((to, from) => { // ... })
3、 組件內(nèi)的守衛(wèi)
在實際情況下,我們使用組件內(nèi)守衛(wèi)較多,在路由組件內(nèi)直接定義以下路由導(dǎo)航守衛(wèi):
- beforeRouteEnter
- beforeRouteUpdate (2.2 新增)
- beforeRouteLeave
要注意此時生命周期對this的訪問以及處理,具體使用如下:
template: `...`, beforeRouteEnter(to, from, next) { // 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用 // 不!能!獲取組件實例 `this` // 因為當(dāng)守衛(wèi)執(zhí)行前,組件實例還沒被創(chuàng)建 }, beforeRouteUpdate(to, from, next) { // 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用 // 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候, // 由于會渲染同樣的 Foo 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。 // 可以訪問組件實例 `this` }, beforeRouteLeave(to, from, next) { // 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用 // 可以訪問組件實例 `this` }
3.其他
本文介紹的是在實際開發(fā)中使用較多的Vue Router
內(nèi)置組件,用好這些組件,往往能夠使得一些復(fù)雜的問題簡單化,使得項目開發(fā)得心應(yīng)手。另本文參考官網(wǎng)進行vue2路由配置實際操作,更加全面的使用請參考官網(wǎng)vue router。
以上就是vue2中vue-router引入使用詳解的詳細(xì)內(nèi)容,更多關(guān)于vue2 vue-router的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue中watch監(jiān)聽器用法之deep、immediate、flush
Vue是可以監(jiān)聽到多層級數(shù)據(jù)改變的,且可以在頁面上做出對應(yīng)展示,下面這篇文章主要給大家介紹了關(guān)于vue中watch監(jiān)聽器用法之deep、immediate、flush的相關(guān)資料,需要的朋友可以參考下2022-09-09