溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

發(fā)布時(shí)間:2023-02-24 11:37:11 來源:億速云 閱讀:102 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航”文章能幫助大家解決問題。

1、導(dǎo)航守衛(wèi)

“導(dǎo)航” 表示路由正在發(fā)生改變

正如其名,vue-router 提供的導(dǎo)航守衛(wèi)主要用來通過跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航。有多種機(jī)會(huì)植入路由導(dǎo)航過程中:全局的, 單個(gè)路由獨(dú)享的, 或者組件級(jí)的。

記住參數(shù)或查詢的改變并不會(huì)觸發(fā)進(jìn)入/離開的導(dǎo)航守衛(wèi)。你可以通過觀察 $route 對(duì)象來應(yīng)對(duì)這些變化,或使用 beforeRouteUpdate 的組件內(nèi)守衛(wèi)。

我這里用到的是全局前置守衛(wèi)

在路由中可以使用router.beforeEach,注冊一個(gè)全局前置守衛(wèi)

const router = new VueRouter({ routes });
 
router.beforeEach((to, from, next) => {
  const isover = to.matched.some(record => record.path == '/over')
  if (isover || to.path == '/overview') {
    if (!store.getters.token) {  // 未登錄
      next('/login'); 
      return
    }
    if (!isHome) {
      next();  
      return
    }
  } else {
    next()  // 無需登錄驗(yàn)證
  }
})

當(dāng)一個(gè)導(dǎo)航觸發(fā)時(shí),全局前置守衛(wèi)按照創(chuàng)建順序調(diào)用,守衛(wèi)是異步解析執(zhí)行,此時(shí)導(dǎo)航在所有守衛(wèi)resolve完之前一直處于等待中。
每個(gè)守衛(wèi)方法接收3個(gè)參數(shù)
to: Route:即將要進(jìn)入的目標(biāo) 路由對(duì)象
from: Route :當(dāng)前導(dǎo)航正要離開的路由
next: Function : 一定要調(diào)用該方法來resolve這個(gè)鉤子,執(zhí)行效果依賴next方法的調(diào)用參數(shù)

1.next(): 進(jìn)行管道中的下一個(gè)鉤子。如果全部鉤子執(zhí)行完了,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)。
2.next(’/’) 或者 next({ path: ‘/’ }): 跳轉(zhuǎn)到一個(gè)不同的地址。當(dāng)前的導(dǎo)航被中斷,然后進(jìn)行一個(gè)新的導(dǎo)航。你可以向 next 傳遞任意位置對(duì)象,且允許設(shè)置諸如 replace: true、name: ‘home’ 之類的選項(xiàng)以及任何用在 router-link 的 to prop 或 router.push 中的選項(xiàng)。
3.next(error): (2.4.0+) 如果傳入 next 的參數(shù)是一個(gè) Error 實(shí)例,則導(dǎo)航會(huì)被終止且該錯(cuò)誤會(huì)被傳遞給 router.onError() 注冊過的回調(diào)。
4.** 確保 next 函數(shù)在任何給定的導(dǎo)航守衛(wèi)中都被嚴(yán)格調(diào)用一次。它可以出現(xiàn)多于一次,但是只能在所有的邏輯路徑都不重疊的情況下,否則鉤子永遠(yuǎn)都不會(huì)被解析或報(bào)錯(cuò) **這里有一個(gè)在用戶未能驗(yàn)證身份時(shí)重定向到 /login 的示例:

// BAD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  // 如果用戶未能驗(yàn)證身份,則 `next` 會(huì)被調(diào)用兩次
  next()
})
// GOOD
router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

二、功能展示 

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

三、原理

對(duì)于路由的導(dǎo)航動(dòng)態(tài)實(shí)現(xiàn),我們首先要確定我們擁有的路由有哪些,并且對(duì)于命名有一定的良好習(xí)慣。其中最重要的就是在我們的路由里面進(jìn)行設(shè)定,設(shè)置我們的路由守衛(wèi),能對(duì)路由進(jìn)行控制和及時(shí)的更新我們的路由數(shù)據(jù),然后就可以直接在功能實(shí)現(xiàn)區(qū)域進(jìn)行調(diào)用實(shí)現(xiàn)了。

四、功能實(shí)現(xiàn)

1.router文件夾

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

在router里面引入我們的store 

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

路由守衛(wèi)

// 路由守衛(wèi)
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name)  // 設(shè)置當(dāng)前的路由名稱,為了在Header組件中去使用
  store.commit("setPath")  // 觸發(fā)store的數(shù)據(jù)更新
  next()  // 放行路由
})

2.store文件夾 

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
const store = new Vuex.Store({
  state: {
    currentPathName: ''
  },
  mutations: {
    setPath (state) {
      state.currentPathName = localStorage.getItem("currentPathName")
    }
  }
})
 
export default store

 3.main.js

Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from "@/store";
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import request from "@/utils/request";
import './assets/css/global.css'
// import * as echarts from 'echarts'
Vue.config.productionTip = false
 
Vue.use(ElementUI,{size: "mini"});
 
Vue.prototype.request = request;
 
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

4.實(shí)現(xiàn)

<template>
  <div >
    <div >
      <span :class="collapseBtnClass" ></span>
      <el-breadcrumb separator="/" >
        <img src="../assets/images/宿舍管理.png" alt=""
             >
        <h4 >宿舍后臺(tái)管理</h4>
          <el-breadcrumb-item :to="'/'" >首頁</el-breadcrumb-item>
          <el-breadcrumb-item >{{ currentPathName }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-dropdown >
      <div >
        <img :src="user.avatarUrl" alt=""
             >
        <span>{{user.nickname}}</span><i class="el-icon-arrow-down" ></i>
      </div>
      <el-dropdown-menu slot="dropdown" >
        <el-dropdown-item >
          <span  @click="person">個(gè)人信息</span>
        </el-dropdown-item>
        <el-dropdown-item >
          <span  @click="logout">退出登錄</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>
 
<script>
export default {
  name: "Header",
  props: {
    collapseBtnClass: String,
    user: Object
  },
  computed: {
    currentPathName () {
      return this.$store.state.currentPathName;  //需要監(jiān)聽的數(shù)據(jù)
    }
  },
  data() {
    return {
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }
  },
  methods: {
    logout() {
      this.$router.push("/login")
      this.$message.success("退出成功")
    },
    person(){
      this.$router.push("/mall/person")
    }
  }
}
</script>
 
<style scoped>
 
</style>

關(guān)于“Vue如何實(shí)現(xiàn)動(dòng)態(tài)路由導(dǎo)航”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI