vue-router路由

component文件夾:經(jīng)常放置非路由組件
pages|views文件夾:經(jīng)常放置路由組件
項目中配置的路由一般放在router文件夾中

配置路由

/src/router/index.js中配置。

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter)

export default new VueRouter({
  mode: history, // 默認 hash
  routes:[
  {
      name:'login',// 給路由命名  路由path過長時,跳轉(zhuǎn)路由可以簡化編碼
      path:'/dashboard',// 路徑
      component:Home,// 組件
      children: [// 子路由  嵌套路由
        name:'',
        path:'about/:id/:title', // params傳參設(shè)置占位符
        component:Banner,
        props: {id: 2,title: '關(guān)于'},// 第一種寫法:值為對象,該對象的所有key-value都會以props的形式傳給組件
        props: true, // 第二種寫法:值為布爾值,若為真,會把路由組件收到的params參數(shù)以props形式傳遞給組件
        props:($route){// 第三中寫法:值為函數(shù),函數(shù)返回的對象會把路由組件收到的參數(shù)以props形式傳遞給組件
          return {id: $route.query.id, title: $route.query.title};// 必須返回對象
        }, 
        props: ({query:{ id,title }}){// 第三種寫法(簡寫):連續(xù)性解構(gòu)賦值
          return { id,title };
        },
        meta: {// 存放自定義數(shù)據(jù)  用于路由守衛(wèi)做權(quán)限校驗
          title: '首頁',
          authority: true,// 是否需要鑒權(quán)
        },
      ]
    }
  ]
 });

main.js中注冊路由

路由組件與非路由組件的區(qū)別:
  1. 路由組件一般放置在pages|views文件夾,非路由組件一般放置在component文件夾中
  2. 路由組一般需要在router文件夾中進行注冊,使用時用的就是組件的名字;非路由組件在使用時,一般是以標簽的形式使用
  3. 注冊完路由,不管是路由組件還是非路由組件身上都有$route、$router屬性
    $route:每個組件實例都有一個route屬性,存儲這自己的路由信息。一般獲取路由信息【路徑、query、params】
    $router: 整個應用只有一個$router屬性,一般進行編程式導航進行路由跳轉(zhuǎn)【push|replace】

切換路由后,上個路由組件默認被銷毀,新的路由組件被掛載。
配置路由規(guī)則時,一級路由組件需要加/,子路由不需要加/,Vue自動會加上。

路由跳轉(zhuǎn)

路由跳轉(zhuǎn)的兩種形式:聲明式導航 router-link,編程式導航 $router.push|replace
聲明式導航能做的,編程時導航都能;但是編程式導航還可以做一些其他業(yè)務邏輯。
<router-link active-class="" to="/home"></router-link> router-link有active-class、to屬性。

路由傳參

params參數(shù):屬于路徑當中的一部分,需要注意,在配置的時候需要占位:id
query參數(shù):不屬于路徑當中的一部分,不需要占位,類似ajax中的queryString /home?k=v

query參數(shù)
  • 傳遞參數(shù)
 <!-- 跳轉(zhuǎn)并攜帶query參數(shù),to的字符串模板寫法 -->
    <router-link :to="`/dashboard/workplace?id=${id}`" >注冊賬戶</router-link>
    <!-- 跳轉(zhuǎn)并攜帶query參數(shù),to的對象寫法 -->
    <router-link :to="{path: `/dashboard/workplace`, query: {id: id}}" >注冊賬戶</router-link>
    <router-link :to="{name: 'register',query: {id}}" >注冊賬戶</router-link>// 命名路由跳轉(zhuǎn)
  • 接收參數(shù)
    $route.query.id
    <div class="footer">
      {{ $route.query.id }}
    </div>
params參數(shù)
  • 傳遞參數(shù)
 <!-- 跳轉(zhuǎn)并攜帶params參數(shù),to的字符串模板寫法 -->
    <router-link :to="`/dashboard/workplace/${id}/${title}`" >注冊賬戶</router-link>
    <!-- 錯誤寫法? 不可使用 path,只能使用name -->
    <router-link :to="{path: `/dashboard/workplace`, params: {id: id}}" >注冊賬戶</router-link>
    <!-- 跳轉(zhuǎn)并攜帶params參數(shù),to的對象寫法  ?-->    
    <router-link :to="{name: 'register',params: {id}}" >注冊賬戶</router-link>// 命名路由跳轉(zhuǎn)
  • 接收參數(shù)
    $route.params.id
    <div class="footer">
      {{ $route.params.id }}
    </div>

特別注意: 路由攜帶params參數(shù)時,若使用to的對象寫法,則不能使用path配置項,必須使用name配置項。

props傳參

路由傳遞參數(shù)以props的方式傳遞給組件,需要在路由配置規(guī)則中配置props項。

  1. 有三種配置方法
  • 第一種寫法:值為對象,該對象的所有key-value都會以props的形式傳給組件,這里只能傳遞固定的值。
    props: {id: 2,title: '關(guān)于'}
  • 第二種寫法:值為布爾值,若為真,會把路由組件收到的params參數(shù)以props形式傳遞給組件
    props: true
  • 第三中寫法:值為函數(shù),函數(shù)返回的對象會把路由組件收到的query參數(shù)以props形式傳遞給組件
props:($route){
   return {id: $route.query.id, title: $route.query.title};// 必須返回對象
}, 
// 簡寫:連續(xù)性解構(gòu)賦值
props: ({query:{ id,title }}){
   return { id,title };
}
  1. 組件獲取props
    配置props,數(shù)組方式接收
    props: ['id', 'title']

注意

  • 對象寫法可以是name、path形式,但是path不能結(jié)合params參數(shù)一起使用
  • 如果路由要求傳遞params參數(shù),但是沒有傳遞,URL會出現(xiàn)問題。要想不出現(xiàn)問題,需要在配置路由的時候,在占位參數(shù)后面加上?,該符號表示params可傳可不傳遞
  • params傳遞是一個空字符串,需要使用undefined,才能保證URL正常
路由模式

路由歷史記錄模式有pushreplace,Vue默認的是push模式。push模式會保留歷史記錄,可以回退也可以前進。replace模式不會保留歷史記錄,會替換當前路由。
聲明式導航使用replace模式需要在<router-link>標簽添加replace屬性。

<router-link :replace="true"  to="/login></router-link">
//簡寫
<router-link replace  to="/login></router-link>
編程式路由導航 $router

作用:不借助router-link實現(xiàn)理由跳轉(zhuǎn)

this.router.push(
  {
    name: 'login',
    params: {},
  }
)
this.router.replace(
  {
    name: 'login',
    params: {},
  }
)

this.router.back():后退
this.router.forward():前進
this.router.go(-2): 前進或后退多少個路由

路由緩存 <keep-alive/>

組件不會被銷毀

// 緩存單個組件  字符串形式
<keep-alive includes=“News”>
  <router-view> </router-view>
</keep-alive>

// 緩存多個組件 數(shù)組形式
<keep-alive :includes=“['News','Message']”>
  <router-view> </router-view>
</keep-alive>

includes:指定緩存的組件 【設(shè)置組件名】

  • 緩存組件后,有可以利用激活失活的組件生命周期來完成顯示與隱藏的監(jiān)聽
  activated () {
     // 組件激活時觸發(fā)
  },
  deactivated () {
     // 組件失活時觸發(fā)
  },

路由守衛(wèi)

  • 全局守衛(wèi)
    為VueRouter對象設(shè)置beforeEach或afterEach函數(shù)
  1. 全局前置守衛(wèi) beforeEach :【初始化】時執(zhí)行、每次路由【切換前】執(zhí)行
    router.beforeEach((to, from, next) => guard(to, from, next, options))
    to:去哪個路由
    from:來自哪個路由
    next():放行
  2. 全局后置守衛(wèi) afterEach: 【初始化】時執(zhí)行、每次路由【切換后】執(zhí)行
    router.afterEach((to, from) => guard(to, from, options))
    后置守衛(wèi)沒有next函數(shù)。
    可以用來修改網(wǎng)頁頁簽標題
router.afterEach((to,from)=>{
  document.title = to.meta.title || 'xx系統(tǒng)'
})
  • 路由獨享路由守衛(wèi) beforeEnter
    路由獨享守衛(wèi) 只有前置,沒有后置!在路由配置中添加beforeEnter函數(shù)

{
   name:'home',
   path: '/home',
   component: Home,
   //獨享前置路由守衛(wèi)
   beforeEnter:(to,from,next)=>{
      //邏輯和全局路由配置一樣
      //to是你要跳轉(zhuǎn)到那個路由組件
      //from是你從哪個路由組件跳轉(zhuǎn)過來的
      //可以在next()前設(shè)置條件,當符合條件就放行,比如:
      if(localStorage.getItem('token')){
        next()
      }
    }
  children: [{
       name:'message/:id/:title', //占位符
       path: "message",
        component: Message
   }]
}
  • 組件內(nèi)路由守衛(wèi)
    beforeRouteEnter : 通過路由規(guī)則,進入該組件時被調(diào)用
    beforeRouteUpdate : 通過路由規(guī)則,該組件被復用時調(diào)用
    beforeRouteLeave : 通過路由規(guī)則,離開該組件時被調(diào)用
  beforeRouteEnter (to, from, next) {
    // ...
  },
  beforeRouteLeave (to, from, next) {
    // ...
  },

----

路由元信息 meta

定義路由的時候可以配置meta字段,meta是一個對象
通過$route.meta獲取元信息
使用場景:可以控制組件的隱藏與顯示

路由器工作模式

history模式與hash模式
  1. 對于一個url來說,什么是hash值?
    hash值是指一個url中,#后面的內(nèi)容,它是用來表示一個頁面的某個位置

  2. hash值不會包含在http 請求中。即:hash值不會帶給服務器

  3. hash模式:
    1.1 url中永遠帶著 #
    1.2 兼容性好
    1.3 無需刷新頁面
    1.4 分享給App時,若App校驗嚴格,地址會被標記為不合法

  4. history模式:
    1.1 url中不會帶著 #
    1.2 兼容性較差
    1.3 應用上線需后端人員配合解決刷新頁面報404的問題

  5. history模式下解決404的問題
    針對node服務器解決方案:
    使用服務器中間件 connect-history-api-fallback
    const history = require('connect-history-api-fallback')
    app.use(history())

node服務器部署前端項目

npm init
npm i express
npm server


image.png
const express = require("express");
const app = express();

// 解決history模式刷新頁面出現(xiàn)404的問題
// 使用服務器中間件 connect-history-api-fallback
// const history = require('connect-history-api-fallback')
// app.use(history())

// 中間件
app.use(express.static(__dirname+'/static'))//指定靜態(tài)資源

app.get("/person", (req, res) => {
    res.send({
        name:'張三',
        age:20
    });
});
app.listen(5005, (err) => {
    console.log("Server is running on port 5005");
})

路由重定向

在項目運行時,訪問/,立馬讓他定向到首頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容