vue-router

1. 路由基本概念以及原理

單頁面應用,一次就請求回來,通過前端路由來進行頁面切換
前端路由實現:
本質是讓改變url頁面不會再發起請求

  1. 方式1: url的hash(#)即錨點 location.hash=‘chenlin’ 頁面不會刷新
  2. 方式2: HTML5的history
1.1 history實現原理
  1. history.pushState({},’’,‘chenlin’) ->是一個棧結構
    頁面向前 history.forward()
    頁面向後 history.back() url將棧頂元素移除,第二個冒出來.即跳轉到上一個url
  2. history.go(-1)等價於 history.back()
  3. history.go(1)等價於 history.forward()
  4. history.replaceState({},’’,‘陳林’) ->url替換(不能返回)

2. vue-router

  1. 安裝: npm install vue-router -S
  2. 使用
    導入路由對象 並使用 Vue.use(VueRouter)
    創建路由實例,實例中配置映射關係
    在Vue實例中掛載路由實例
    當引入的是文件夾,後面沒有接文件時,默認使用index文件,所以在router文件件中新建index.js文件即可
導入並配置並掛載
import VueRouter from 'vue-router'
import Vue from 'vue'

import Home from '../components/Home'
import About from '../components/About'
Vue.use(VueRouter)//初始化

const routes = [//配置映射關係
  {path:'/',redirect:'/home'},
  {path:'/home',component:Home},
  {path:'/about',component:About}
]


const router = new VueRouter({
  mode: 'history',
  routes
  //傳入的是routes routes routes!!!
})

export default router
展示的地方
<template>
  <div id="app">
    <div>
      <router-link to="/home">首頁</router-link>
      <router-link to="/about">關於</router-link>
      <router-view></router-view>
    </div>
  </div>
</template>
最後掛載
import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
2.1 router-link的其他屬性:
  1. tag ->指定router-link渲染成的標籤
  2. replace 使用replaceStatu模式(不能返回頁面), 該屬性沒有屬性值
  3. 激活狀態的標籤會默認添加屬性: router-link-active
2.2可以指定組件激活狀態所添加的類名
const router = new VueRouter({
  mode: 'history',
  routes,
  linkActiveClass:'myActive'//指定激活狀態添加的類名(添加樣式)
})
2.3路由懶加載

即引入組件的方式變爲下面,然後配置路由無需更改即可

//import Home from '../components/Home'
//import About from '../components/About'
//import User from '../components/User'
//改爲下面
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
//注意:這個箭頭函數後面不能用大括號進行包裹!!!

const routes = [//配置映射關係
  {path: '/', redirect: '/home'},
  {path: '/home', component: Home},
  {path: '/about', component: About},
  {path: '/user/:userId', component: User}
]

3. 編程式路由

即通過事件來跳轉頁面

this.$router.push('home') 通過事件觸發(實際使用上一點問題,vue-router版本原因)

或者

this.$router.replace('home')
//沒有返回功能,相當於新開標籤

4. 路由嵌套

路由嵌套,比如一個組件下有多個子組件需要配置路由(比如 /home/news 和 /home/message)

配置
//引入
const HomeNews = ()=>import('../components/HomeNews')
const HomeMessage = ()=>import('../components/HomeMessage')
//配置
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children: [
	 {path:'',redirect:'news'},//配置默認顯示組件
      {path: 'news', component: HomeNews},
      {path: 'message', component: HomeMessage}

    ]
  }
]
使用
<template>
  <div>
    <h2>這是home組件</h2>
    <p>內容區域</p>
    <router-link to="/home/news" tag="button">新聞</router-link>
    <router-link to="/home/message" tag="button">信息</router-link>
    <router-view></router-view>
  </div>
</template>

5. vue-router中傳遞參數

5.1 query方式傳遞

//發送
<router-link to="/profile?name='陳林',age=18,height='174'">profile組件</router-link>

<router-link :to="{path:'/profile',query:{name:'陳林',age:18,height:174}}">profile組件</router-link>
//兩種發送方式等價
//記得to屬性需要 v-bind綁定

接收使用:

<div>{{$route.query}}</div>
5.2 params方式傳遞

前提
{
path: ‘/user/:userId’,//在路徑後面添加 /:key
component: User
}
發送:

<router-link :to="'/user/'+userId" >用戶界面</router-link>

在後面添加 /key,需要to屬性綁定 v-bind
接收使用

<div>{{$route.query.id}}</div>
5.3 編程式路由的參數傳遞
this.$router.push('/home/'+this.myId)//parame方式

this.$router.push({path:'/home',query:{name:'chenlin',age:18}})//query方式傳遞
$route與 $router區別

$route 是當前活躍的路由
$router是 導出的 router

6. vue-router全局導航守衛

即路由跳轉之間進行監聽,有幾個回調函數
router.beforeEach((to,from,next)=>(){})函數是一個前置鉤子 ->跳轉之前的回調
router.afterforEach((to,from)=>{}) 沒有next 是一個後置鉤子 ->跳轉完後的回調
from 是離開當前路由對象
to 是跳轉到目標路由的對象
next() 是執行下一步,中間件裏的next類似吧
上面兩個函數是兩個全局守衛,還有路由獨享守衛 組件內的守衛等,需要使用看官網
案例:實現動態修改網頁標題
首先在每個路由配置時,添加meta屬性

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    children: [
      {path:'',redirect:'news'},
      {path: 'news', component: HomeNews},
      {path: 'message', component: HomeMessage}
    ],
    meta:{
      title:'首頁'
    }
  },
  {
    path: '/about',
    component: About,
    meta:{
      title:'關於'
    }
  },
  {
    path: '/user/:userId',
    component: User,
    meta:{
      title:'用戶'
    }
  },
  {
    path:'/profile',
    component:Profile,
    meta:{
      title:'檔案'
    }
  }
]

然後在路由配置頁面(router/index.js)調用
通過 to.matched[0].meta.title拿到meta裏面的元素

router.beforeEach((to,from,next)=>{
  document.title = to.matched[0].meta.title //組件之間嵌套,所以需要通過matched[0]拿到
 next()
})

7. keep-alive

kepp-alive是Vue內置的一個組件,可以是被包裹的組件保留狀態,或者避免重新渲染
router-view也是一個全局組件,如果直接包在keep-alive裏面,所有路徑匹配到的視圖組件都會被緩存
使用:

<keep-alive>
	<router-view></router-view>
</keep-alive>

keep-alive有兩個重要屬性
include 匹配的字符串/正則表達式的組件會被緩存 值可以是組件export defaule 拋出出去的name值,多個值之間用逗號隔開
exclude 匹配的字符串/正則表達式的組件不會被緩存

8. 爲路由組件切換展示動畫

第一步:用<transition mode="out-in">router-view包裹起來,再在style設置兩組css:

.v-enter,
.v-leave-to{
     opacity: 0;
     transform: translateX(140px);
 }
 .v-enter-active,
 .v-leave-active{
     transition:all 0.5s ease;
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章