編程使我快樂

Vue-router的基本使用
路由,其實就是指向的意思,當我點擊頁面上的 首頁按鈕的時候,頁面中就是顯示首頁 的內容,如果點擊頁面上的關于按鈕,頁面就顯示 關于的內容,Home按鈕==>首頁內容,關于按鈕==>關于的頁面,也可以說是一種映射,所以在頁面上有兩個部分,一個是點擊部分,一個是點擊之后,顯示內容的部分,路由模塊的本質 就是建立起url和頁面之間的映射關系,
點擊之后,怎么做到正確的對應,比如,當我點擊首頁按鈕,頁面中就顯示home的內容,這就要在js檔案中進行路由的配置
概念:通過改變URL,再不重新請求頁面的情況下,更新頁面的視圖,
Vue-router兩種模式
更新視圖但不重新請求頁面資料,是前端路由原理的核心之一,目前在瀏覽器環境中這一個功能的實作主要有兩種方式:
Hash------>默認值,利用URL中的hash(‘#’)
history------>利用URL中的路徑(/home)
hash模式
vue-router 默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,于是當 URL 改變時,頁面不會重新加載, hash(#)是URL 的錨點,代表的是網頁中的一個位置,單單改變#后的部分,瀏覽器只會滾動到相應位置,不會重新加載網頁,也就是說 #是用來指導瀏覽器動作的,對服務器端完全無用,HTTP請求中也不會不包括#;同時每一次改變#后的部分,都會在瀏覽器的訪問歷史中增加一個記錄,使用”后退”按鈕,就可以回到上一個位置;所以說Hash模式通過錨點值的改變,根據不同的值,渲染指定DOM位置的不同資料
History模式:
由于hash模式會在url中自帶#,如果不想要很丑的 hash,我們可以用路由的 history 模式,只需要在配置路由規則時,加入"mode: ‘history’",這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新加載頁面
如何設定路由的模式
const router=new VueRouter({
mode:'history',
routes:[...]
})
mode中的值的區別
- mode:'hash’多了 “#”
http://localhost:8080/#/login
- mode:‘history’
http://localhost:8080/home
使用路由模塊來實作頁面跳轉的方式
方式1:直接修改地址欄
方式2:this.$router.push(‘路由地址’)
方式3:
<router-link to="路由地址"></router-link>
Vue-router使用的方式
- 下載
npm install vue-router -S
- 在main.js中引入
import VueRouter from 'vue-router
- 安裝插件
Vue.use(VueRouter)
- 創建路由物件并配置路由規則
let router = new VueRouter({
routes:[{path:'/home',component:Home}]
}
- 將其路由物件傳遞給Vue的實體,options中加入 router:router
//new Vue啟動
new Vue({
el:'#app',
//讓vue知道我們的路由規則
router:router,
render:c=>c(App)
})
- 在vue中使用**
<router-view> </router-view**組件占位,
//app.vue中
<template>
<div>
<!-- 留坑,非常重要 -->
<router-view></router-view>
</div>
</template>
<script>
export default {
data(){
return {}
}
}
</script>
Vue-Router的核心
1. Vue-router引數如何傳遞
①、使用name傳遞引數
在路由檔案src/router/index.js檔案里面進行配置name屬性
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
在組件中使用 $router.name 來接收,比如下面代碼:
<p>{{$router.name}}</p>
②、通過 標簽中的to傳參
這種引數方法的基本語法:
<router-link :to="{name:xxx,params:{key:value}}">valueString</router-link>
比如先在src/App.vue檔案中
<router-link :to="{name:'hi1',params:{username:'jspang',id:'555'}}">Hi頁面1</router-link>
然后把src/router/index.js檔案里給hi1配置的路由起個name,就叫hi1.
{path:'/hi1',name:'hi1',component:Hi1}
最后在模板里(src/components/Hi1.vue)用$route.params.username進行接收.
<router-link :to="{{$route.params.username}}-{{$route.params.id}}">Hi頁面1</router-link>
③vue-router 利用url傳遞引數----在組態檔里以冒號的形式設定引數,
我們在 /src/router/index.js 檔案里配置路由
{
path:'/params/:newsId/:newsTitle',
component:Params
}
我們需要傳遞引數是 新聞ID(newsId) 和新聞標題(newsTitle).所以我們在路由組態檔里制定了這兩個值,
在src/components目錄下建立我們params.vue組件,也可以說是頁面,我們在頁面里輸出了url傳遞的的新聞ID和新聞標題,
<template>
<div>
<h2>{{ msg }}</h2>
<p>新聞ID:{{ $route.params.newsId}}</p>
<p>新聞標題:{{ $route.params.newsTitle}}</p>
</div>
</template>
<script>
export default {
name: 'params',
data () {
return {
msg: 'params page'
}
}
}
</script>
在App.vue檔案里加入我們的標簽,這時候我們可以直接利用url傳值了
<router-link to="/params/198/jspang website is very good">params</router-link>|
2. 單頁面多路由區域操作
在一個頁面里我們有2個以上 <router-view> 區域,我們通過配置路由的js檔案,來操作這些區域的內容
①App.vue檔案,在 <router-view> 下面新寫了兩行標簽,并加入了些CSS樣式
<template>
<div id="app">
<img src="./assets/logo.png">
<router-link :to="{name:'HelloWorld'}"><h1>H1</h1></router-link>
<router-link :to="{name:'H1'}"><h1>H2</h1></router-link>
<router-view></router-view>
<router-view name="left" style="float:left;width:50%;background-color:#ccc;height:300px;"/>
<router-view name="right" style="float:right;width:50%;background-color:yellowgreen;height:300px;"/>
</div>
</template>
②需要在路由里配置這三個區域,配置主要是在components欄位里進行
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
components: {default: HelloWorld,
left:H1,//顯示H1組件內容'I am H1 page,Welcome to H1'
right:H2//顯示H2組件內容'I am H2 page,Welcome to H2'
}
},
{
path: '/h1',
name: 'H1',
components: {default: HelloWorld,
left:H2,//顯示H2組件內容
right:H1//顯示H1組件內容
}
}
]
})
3.vue-router配置子路由(二級路由)
實際生活中的應用界面,通常由多層嵌套的組件組合而成,同樣地,URL中各段動態路徑也按某種結構對應嵌套的各層組件,例如:

如何把H1頁面和H2頁面嵌套在主頁中去
①首先用 <router-link> 標簽增加了兩個新的導航鏈接
<router-link :to="{name:'HelloWorld'}">主頁</router-link>
<router-link :to="{name:'H1'}">H1頁面</router-link>
<router-link :to="{name:'H2'}">H2頁面</router-link>
②在 HelloWorld.vue加入 <router-view> 標簽,給子模板提供插入位置
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<router-view></router-view>
</div>
</template>
③在components目錄下新建兩個組件模板 H1.vue 和 H2.vue
兩者內容類似,以下是H1.vue頁面內容:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
msg: 'I am H1 page,Welcome to H1'
}
}
}
</script>
④修改router/index.js代碼,子路由的寫法是在原有的路由配置下加入children欄位,
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
children: [{path: '/h1', name: 'H1', component: H1},
{path: '/h2', name: 'H2', component: H2}
]
}
]
vue-router跳轉方法
<button @click="goToMenu" class="btn btn-success">Let's order!</button>
.....
<script>
export default{
methods:{
goToMenu(){
this.$router.go(-1)//跳轉到上一次瀏覽的頁面
this.$router.replace('/menu')//指定跳轉的地址
this.$router.replace({name:'menuLink'})// 指定跳轉路由的名字下
this.$router.push('/menu')通過push進行跳轉
this.$router.push({name:'menuLink'})通過push進行跳轉路由的名字下
}
}
}
</script>
404頁面的設定
用戶會經常輸錯頁面,當用戶輸錯頁面時,我們希望給他一個友好的提示頁面,這個頁面就是我們常說的404頁面,vue-router 也為我們提供了這樣的機制,
①設定我們的路由組態檔(/src/router/index.js)
{
path:'*',
component:Error
}
這里的path:’*’ 就是輸入地址不匹配時,自動顯示出Error.vue的檔案內容
②在/src/components/檔案夾下新建一個Error.vue的檔案,簡單輸入一些有關錯誤頁面的內容,
<template>
<div>
<h2>{{ msg }}</h2>
</div>
</template>
<script>
export default {
data () {
return {
msg: 'Error:404'
}
}
}
</script>
路由物件的使用
在使用vue-router的應用中,路由物件會被注入每個組件中,賦值為this.$route,并且當路由切換的時候,路由物件會被更新,所以,路由物件中暴露了以下幾個屬性
- $route.path:字串,等于當前路由物件的路徑,會被決議為絕對路徑,如 “/home/news”,
//路由跳轉
this.$router.push({path:`/user/${userId}`})
這種方式需要在路由中作如下的配置
{
path: '/user/:userId',
name: '***',
component: ***
}
- $route.params:物件,包含路由中的動態片段和全域匹配片段的鍵值對,
this.$router.push({name:'Login',params:{id:'leelei'}}
//不帶引數 變成 ip/login
- r o u t e . q u e r y : 對 象 , 包 含 路 由 中 查 詢 參 數 的 鍵 值 對 , 例 如 , 對 于 , ‘ route.query:物件,包含路由中查詢引數的鍵值對,例如,對于,` route.query:對象,包含路由中查詢參數的鍵值對,例如,對于,‘route.query.favorite=='yes`,
this.$router.push({path:'/login',query:{id:'leelei'})
//帶查詢引數變成 ip/login?id=leelei
//帶斜杠/代表從根目錄出發,不會嵌套之前的路徑
- $route.router:路由規則所屬的路由器(以及器所屬的組件),
- $route.matched:陣列,包含當前匹配的路徑中所包含的所有片段對應的配置引數物件
let routes = [
{
path: '/',
component: () => import('../pages/layout/Layout.vue'),
children: [
{
name: 'pageA',
path: 'a',
component: PageA,
children: [
{
name: 'pageAA01',
path: 'aa-01',
component: PageAA01
},
{
name: 'pageAA02',
path: 'aa-02',
component: PageAA02
},
{
name: 'pageAA03',
path: 'aa-03',
component: PageAA03
},
]
}
]
}
]
matched顧名思義 就是 匹配,假如我們目前的路由是/a/aa-01,那么此時 this.$route.matched匹配到的會是一個陣列,包含 ‘/’,’/a’,’/a/aa-01’,這三個path的路由資訊,然后我們可以直接利用路由資訊渲染我們的面包屑導航,
//demo
<template>
<div class="nav-wrap">
<router-link v-for="(item, index) in navList" :key="index">
{{ item.name }} {{index !== list.length - 1 ? '/' : ''}}
</router-link>
</div>
</template>
<script>
export default {
data() {
navList: []
},
watch: {
$route: {
handler() {
this.getNavList()
},
immediate: true
}
},
methods: {
getNavList() {
this.$route.matched.filter(item => item.name);
}
}
}
</script>
- $route.name:當前路徑的名字,如果沒有使用具名路徑,則名字為空,
路由導航守衛
全域前置守衛
使用router.beforeEach注冊一個全域前置導航守衛:
const router=new VueRouter({...})
router.beforeEach((to,from,next)=>{
//.....
})
to:Route:即將要進入的目標 路由物件
from:Route:當前導航正要離開的路由
next:Function:一定要呼叫該方法來resolve這個鉤子,執行效果依賴next方法呼叫引數,
next():進行管道中的下一個蓋過章,如果全部鉤子執行完了,則導航的狀態就是confirmed(確認的),next(): 中斷當前的導航,如果瀏覽器的 URL 改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應的地址,- 確保 next函式 在任何給定的導航守衛中都被嚴格呼叫一次,它可以出現多于一次,但是只能在所有的邏輯路徑都不重疊的情況下,否則鉤子永遠都不會被決議或報錯,這里有一個在用戶未能驗證身份時重定向到 /login 的示例:
// BAD
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
// 如果用戶未能驗證身份,則 `next` 會被呼叫兩次
next()
})
// GOOD
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
路由懶加載
像vue這種單頁面應用,如果沒有應用懶加載,運用webpack打包后的檔案將會例外的大,造成進入首頁時,需要加載的內容過多,時間過長,會出啊先長時間的白屏,即使做了loading也是不利于用戶體驗,而運用懶加載則可以將頁面進行劃分,需要的時候加載頁面,可以有效的分擔首頁所承擔的加載壓力,減少首頁加載用時
實作路由懶加載的三種方式
- vue異步組件
vue配置路由,使用vue的異步組件技術,可以實作按需加載但是,這種情況下一個組件會生成一個js檔案,語法如下:
/* vue異步組件技術 */
{ path: '/home', name: 'home', component: resolve => require(['@/components/home'],resolve) },
{ path: '/index', name: 'Index', component: resolve => require(['@/components/index'],resolve) },
{ path: '/about', name: 'about', component: resolve => require(['@/components/about'],resolve) }
- es提案的使用import()
const 組件名=() => import('組件路徑');
// 下面2行代碼,沒有指定webpackChunkName,每個組件打包成一個js檔案,
/* const Home = () => import('@/components/home')
const Index = () => import('@/components/index')
const About = () => import('@/components/about') */
// 下面2行代碼,指定了相同的webpackChunkName,會合并打包成一個js檔案,
把組件按組分塊
const Home = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
const Index = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')
const About = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/about')
{ path: '/about', component: About }, { path: '/index', component: Index }, { path: '/home', component: Home }
- webpack提供的require.ensure()
vue-router配置路由,使用webpack的require.ensure技術,也可以實作按需加載,
這種情況下,多個路由指定相同的chunkName,會合并打包成一個js檔案,
/* 組件懶加載方案三: webpack提供的require.ensure() */
{ path: '/home', name: 'home', component: r => require.ensure([], () => r(require('@/components/home')), 'demo') },
{ path: '/index', name: 'Index', component: r => require.ensure([], () => r(require('@/components/index')), 'demo') },
{ path: '/about', name: 'about', component: r => require.ensure([], () => r(require('@/components/about')), 'demo-01') }
// r就是resolve
const list = r => require.ensure([], () => r(require('../components/list/list')), 'list');
// 路由也是正常的寫法 這種是官方推薦的寫的 按模塊劃分懶加載
const router = new Router({
routes: [
{
path: '/list/blog',
component: list,
name: 'blog'
}
]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321290.html
標籤:其他
下一篇:前端常見面試題
