路由详解(九阳真经)
本文章是小編在使用路由的時候,總結的一篇文章。里面涵蓋了我們日常在時候路由的常用方法與講解。希望我的文章能給大家帶來些許幫助。祝大家:月薪過萬,一飛沖天。
一、路由及路由插件的介紹
- 路由的概念:
- 什么是單頁應用呢?單頁應用的全稱是 single-page application,簡稱 SPA,它是一種網站應用的模型,它可以動態重寫當前的頁面來與用戶交互,而不需要重新加載整個頁面。單頁應用的流暢性讓 Web 應用更像桌面端或 Native 應用了。相對于傳統的 Web 應用,單頁應用做到了前后端分離,后端只負責處理數據提供接口,頁面邏輯和頁面渲染都交給了前端。前端發展到現在,單頁應用的使用已經很廣泛,目前時興的 React、Vue、Angular 等前端框架均采用了 SPA 原則。單頁應用意味著前端掌握了主動權,也讓前端代碼更復雜和龐大,模塊化、組件化以及架構設計都變得越來越重要。
- 路由router插件介紹
- vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用于構建單頁面應用。vue的單頁面應用是基于路由和組件的,路由用于設定訪問路徑,并將路徑和組件映射起來。傳統的頁面應用,是用一些超鏈接來實現頁面切換和跳轉的。在vue-router單頁面應用中,則是路徑之間的切換,也就是組件的切換。
二、router插件使用
router目錄(創建一些路由規則,路徑)
安裝插件
單獨安裝
npm install vue-router@3.2.0 --save腳手架中勾選
新手使用 router 的時候,建議直接在使用腳手架創建 vue2 項目的時候,直接勾選,這樣不容易安裝錯誤對應的版本,導致一些錯誤。
創建路由模塊文件 router.js(再router目錄index.js)
整個router.js示例(router目錄index.js)
import VueRouter from "vue-router"; //導入 import Vue from 'vue' import NBA from '../views/NBA' import NEWS from '../views/NEWS'// 繼承vuerouter插件 Vue.use(VueRouter)// 實例化路由對象、創建規則· const router = new VueRouter({routes:[{path:'/nba',component:NBA},{path:'/news',component:NEWS},] })export default routermain.js(入口文件中集成路由插件到vue)
整個main.js
import Vue from 'vue' import App from './App.vue' import router from './router'Vue.config.productionTip = falsenew Vue({router:router,render: h => h(App) }).$mount('#app')App.vue(路由的占位符router-view)
<template><div id="app"><h2>路由的學習</h2><router-view></router-view></div> </template><script>export default {name: 'App',} </script><style lang="scss"> #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>二、router的常用方法
普通的路由配置
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue'const routes=[{// 基本的路由 配置 只需要這樣兩個屬性即可path:'/home', component:Home},{path:'/center', component:Center}, ]聲明式導航
用法:點擊router-link,對應路徑的組件加載到 < router-view>< /router-view>
// 聲明式導航 <router-link :to="{path:'/home'}">首頁</router-link> <router-link :to="{path:'/center'}">個人中心</router-link>// 這里是對應的組件的顯示的標簽 <router-view></router-view>編程式導航
用法:寫兩個點擊事件,在點擊事件函數中寫要跳到的路由,然后顯示在< router-view>< /router-view>
這里的$router 代表的就是 new VueRouter()實例
<button @click="onGoHome">首頁</button> <button @click="onGoCenter">個人中心</button>// 這里是對應的組件的顯示的標簽 <router-view></router-view><script>export default {methods:{onGoHome(){// $router 代表的就是 new VueRouter()實例// 這里就是 編程式導航的路由跳轉// this.$router.push('/home') // 這里是第一種寫法this.$router.push({path:'/home'}) // 也可以傳入一個對象 第二種寫法},onGoCenter(){// 這里就是 編程式導航的路由跳轉// this.$router.push('/center') // 這里是第一種寫法this.$router.push({path:'/center'}) // 也可以傳入一個對象 第二種寫法}} }</script>命名路由
概念:就是給路由定義了一個名字、使用的時候更加方便
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue'const routes=[{path:'/home', name:'home', // 給路由添加一個 name 屬性 就是命名路由了component:Home},{path:'/center', name:'center', // 給路由添加一個 name 屬性 就是命名路由了component:Center}, ]聲明式導航
// 聲明式導航 <router-link :to="{name:'home'}">首頁</router-link> <router-link :to="{name:'center'}">個人中心</router-link>// 這里是對應的組件的顯示的標簽 <router-view></router-view>編程式導航
<button @click="onGoHome">首頁</button> <button @click="onGoCenter">個人中心</button>// 這里是對應的組件的顯示的標簽 <router-view></router-view><script>export default {methods:{onGoHome(){this.$router.push({name:'home'}) },onGoCenter(){this.$router.push({name:'center'}) }} } </script>動態路由
概念:可以將滿足某種要求的數據統一進行渲染
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Info from '.../Info.vue'const routes=[{// 動態路由就是在路徑后面添加 /:參數名 參數名可以隨意取path:'/home/:id', name:'home', component:Home},{// 動態路由就是在路徑后面添加 /:參數名 參數名可以隨意取 可以書寫多個動態的path:'/info/:id/:uid', name:'info', component:Info}, ]聲明式導航
// 直接拼接一個 (/參數即可) <router-link to="/home/123">首頁</router-link>// 這里是對應的組件的顯示的標簽 <router-view></router-view>動態路由的接受值的方法默認是params
<script>export default {created(){console.log(this.$route.params.id) // 獲取對應的 id 的值} } </script>編程式導航( this.$router.push({path:‘/home’,query:{id:123}}))
// 這里是對應的組件的顯示的標簽 <router-view></router-view> <button @click="onGoHome">首頁</button><script>export default {methods:{onGoHome(){// 第一種寫法-----111// this.$router.push('/home/'+123) // '123' 也可以是一個變量// 第二種寫法-----222this.$router.push({path:'/home',query:{id:123}})}} } </script>接受剛才的對應參數(this.$route.query.id)
<script>export default {created(){// 獲取第一種寫法的參數-----111// console.log(this.$route.params.id)// 獲取第二種寫法的參數-----222console.log(this.$route.query.id)} } </script>嵌套路由
概念:就一個父路由里還有子路由,就是給children屬性
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue'// 引入對應的組件 import Child1 from '.../Child1.vue' import Child2 from '.../Child2.vue'const routes=[{path:'/home', component:Home, // 嵌套路由就是 給路由添加一個 children 屬性,屬性值是一個數組,數組中在書寫路由的配置即可children:[{path:'child1', // 注意這兒的書寫component:Child1},{path:'child2', // 注意這兒的書寫component:Child2 }]},{path:'/center', component:Center}, ]對應的聲明式導航
// 以下代碼 應該寫在 home 組件中 對應的層級關系才正確 <router-link to="/home/child1">首頁</router-link>// 這里是對應的組件的顯示的標簽 <router-view></router-view>對應的編程式導航
// 這里是對應的組件的顯示的標簽 <router-view></router-view> <button @click="onGoHomeChild1">首頁/child1</button><script>export default {methods:{onGoHomeChild1(){ this.$router.push({path:'/home/child1'})}} } </script>命名視圖
概念:命名視圖就是一個path對應多個component組件
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue' import Slide from '.../Slide.vue'const routes=[{path:'/home', //這里就是命名視圖,當路徑是 /home 的時候,會顯示下面的兩個組件,需要頁面做一些設置components:{default:Home,slider:Slide}},{path:'/center', component:Center}, ]聲明式導航
<router-link to="/home">首頁</router-link>// 這里是對應的組件的顯示的標簽 <router-view></router-view> // 這個會加載 components 中的 default 的屬性值 <router-view name="slider"></router-view> // 這個會加載 components 中的 slider 的屬性值編程式導航
// 這里是對應的組件的顯示的標簽 <router-view></router-view> // 這個會加載 components 中的 default 的屬性值 <router-view name="slider"></router-view> // 這個會加載 components 中的 slider 的屬性值<button @click="onGoHomeChild1">首頁/嵌套路由</button><script>export default {methods:{onGoHomeChild1(){// 第一種寫法// this.$router.push('/home/child1') // 第二種寫法this.$router.push({path:'/home/child1'})}} } </script>路由重定向
概念:就是匹配不到對應的路徑的時候、跳到指定路徑。路由由上往下匹配、重定向一般寫在最后面。
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue'const routes=[{// 基本的路由 配置 只需要這樣兩個屬性即可path:'/home', component:Homechildren:[{path:'child1', // 注意這兒的書寫component:Child1},{path:'child2', // 注意這兒的書寫component:Child2 },{ // 嵌套組件的路由重定向path:'/home',redirect:'/home/child1' }]},{path:'/center', component:Center},{ // 在上面的路由都不匹配的時候,就重定向到 /home 然后加載對應的組件path:'*',redirect:'/home'} ]路由懶加載
概念:在打開頁面的時候、只加載頁面顯示的模塊
目錄:router(index.js)
// 引入 對應的組件 import Home from '.../Home.vue' import Center from '.../Center.vue'const routes=[{// 基本的路由 配置 只需要這樣兩個屬性即可path:'/home', component:()=>import('.../Home.vue') // 按需加載模塊,這就是懶加載},{path:'/center', component:()=>import('.../Center.vue') // 按需加載模塊,這就是懶加載}, ]三、router-link導航的三種方式
默認路由導航
命名路由(:to=“{name:‘newsname’}”)
? 2.命名路由的使用
- 注意事項:to前面必須加冒號 :
路徑路由(:to=“{path:‘/nba’}”)
- 注意事項:to前面必須加冒號 :
四、router-link的三種傳參方式
動態路由傳參
在router目錄下引入需要的views
5.在Detail(商品詳情文件中)
<template> <div><h2>商品詳情</h2><p>{{$route.params.id}}</p> </div> </template>2、使用params進行傳參
-
傳參:
<router-link :to="{name:'ProductDetail',params:{id:'1002'}}">商品2</router-link> -
接受值:
<p>{{$route.params.id}}使用parmas接受</p>
3.使用query進行傳參
傳參
<router-link :to="{name:'ProductDetail',query:{id:'1003'}}">商品3</router-link>接受參數
<p>{{$route.query.id}}使用query接受</p>五、編程式導航&聲明式導航
聲明式導航:
<router-link to="/home">首頁</router-link>編程式導航:
//寫一個點擊事件函數 <button @click="onGoHomeChild1">首頁/嵌套路由</button>//在點擊事件函數里面寫 <script>export default {methods:{onGoHomeChild1(){// 第一種寫法// this.$router.push('/home/child1') // 第二種寫法this.$router.push({path:'/home/child1'})}} } </script>編程式導航中的push與replace
六、route與route與route與router
$route:表示當前活躍的路由對象、就是地址欄對應的路徑的路由對象
$router:表示整個路由的實例對象、就是router文件夾下面的index.js文件中使用的new VueRouter()的router
this.$router.push()
// 編程式導航中使用 // 這個函數實現的跳轉可以回退,具有歷史記錄 this.$router.push('/login')this.$router.replace()
// 編程式導航使用 // 這個函數實現的跳轉不會保留歷史,不能回退 this.$router.replace('/login')this.$router.go() this.$router.back() his.$router.forward()
// 這個函數有一個參數,正數表示前進一步,負數表示后退一步// 前進一步 this.$router.go(1)// 后退一步 this.$router.go(-1)// 后退一步 相當于 go(-1) this.$router.back()// 前進一步,相當于 go(1) this.$router.forward()七、路由守衛
概念:
路由守衛就是路由跳轉的一些驗證,比如登錄鑒權(沒有登錄不能進入個人中心頁)等等等
守衛函數的三個參數
全局守衛
全局前置守衛
router.beforeEach((to,from,next)=>{// 在這里的面鑒權 })路由鑒權
這種方式是通過路由白名單來實現的;路由白名單就是一個數組,將不需要鑒權的path放進去,在beforeEach觸發的時候,判斷一下是不是在數組中,在數組中直接放行即可;不在數組中的,就是需要鑒權的。
目錄:
-
src
- permission.js
- // 引入路由表文件 router/index.jsimport router from '.../router'router.beforeEach((to,from,next)=>{const routerArr=['/login','/regist','/home']if(routerArr.indexOf(to.fullPath) !== -1){// 直接放行next()return}let token = localStorage.getItem("TOKEN")if(token){// 直接放行next()}else{// 否則跳轉至 登錄界面next('/login') // next 中支持 字符串參數,對象參數,參數+傳值}})
-
在main.js文件中引入
// 使用 在 main.js 文件中引入 import './permission.js'new Vue({router,render:h=>h(App) }).$mount("#app")
第二種鑒權方式(元信息鑒權)
permission.js
// 引入 路由表文件 router/index.js import router from '.../router'router.beforeEach((to,from,next)=>{// matched 是一個數組if(to.matched.some(item=>item.meta.isAuthentication)){// 直接放行next()return}let token = localStorage.getItem("TOKEN")if(token){// 直接放行next()}else{// 否則跳轉至 登錄界面next('/login') // next 中支持 字符串參數,對象參數,參數+傳值}})在 main.js 文件中引入
import './permission.js'new Vue({router,render:h=>h(App) }).$mount("#app")獨享守衛
const routes=[{path:'/home/:id',component:Home,props:true // 注意這樣一行代碼beforeEnter:(to,from,next)=>{// 和全局守衛的使用一樣}} ]組件內守衛
beforeRouteEnter(to, from, next) {// 在渲染該組件的對應路由被 confirm 前調用// 因為當守衛執行前,組件實例還沒被創建if (sessionStorage.getItem("token")) {next();} else {alert("請先登錄");next("/login");}},beforeRouteUpdate(to, from, next) {// 在當前路由改變,但是該組件被復用時調用// 可以訪問組件實例 `this`},beforeRouteLeave(to, from, next) {// 導航離開該組件的對應路由時調用// 可以訪問組件實例 `this`},八、路由的hash模式和history模式
區別:
地址欄表現不一樣:
hash 模式地址欄會出現一個 # ;history 模式不會出現,和請求服務器的 API 的地址一樣。
底層原理不一樣:
hash和history的優缺點
- 優點:瀏覽器兼容性較好,連 IE8 都支持
- 缺點:路徑在井號 # 的后面,比較丑
- 優點:路徑比較正規,沒有井號 #
- 缺點:兼容性不如 hash,且需要服務端支持,否則一刷新頁面就404了
使用
import Vue from 'vue' import VueRouter from 'vue-router'Vue.use(VueRouter)const routes=[{path:'/home',component:Home} ]const router=new VueRouter({mode:'hash' // 這個表示路由的 hash 模式// mode:'history' // 這個表示路由的 history 模式routes })九、@/ 代表的意思
@/ === /src // 這個應該看的懂了 // 這個@ 是可以改變的 需要去webpack中配置總結
以上是生活随笔為你收集整理的路由详解(九阳真经)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: st-link v2怎么连接_【粉猪测评
- 下一篇: 应急响应 - Windows 入侵排查