国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Vue3添加動(dòng)態(tài)路由及項(xiàng)目搭建

這篇具有很好參考價(jià)值的文章主要介紹了Vue3添加動(dòng)態(tài)路由及項(xiàng)目搭建。希望對大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

安裝項(xiàng)目

yarn create vite vue3-project

安裝依賴包

yarn add @types/node -D

在tsconfig.json中配置別名

 "baseUrl": "./",
    "paths": {
      "@/*":["src/*"]
    },

在vite中進(jìn)行配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
導(dǎo)入resolve
import {resolve} from 'path'
配置resolve
export default defineConfig({
  plugins: [vue()],
  resolve:{
    alias:{
      "@":resolve(__dirname,'./src')
    }
  },
})

安裝elementUi-Plus

  1. 下載依賴包
 yarn add element-plus
  1. 完整引入
    在項(xiàng)目入口文件main.js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')
  1. 按需導(dǎo)入
    • 首先安裝依賴包
npm install -D unplugin-vue-components unplugin-auto-import
  • 在項(xiàng)目入口文件main.js
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  // ...
  plugins: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],

靜態(tài)路由搭建

  1. 安裝依賴
yarn add vue-router
  1. 路由表搭建
import {RouteRecordRaw,createRouter, createWebHashHistory} from 'vue-router';
const routes:Array<RouteRecordRaw> = [
    {
        path:'/login',
        component:()=>import('@/views/Login.vue')
    },
    {
        path:'/',
        redirect:'/homg'
    },
    {
        path:'/home',
        component:()=>import('@/views/HomePage.vue')
    }
]
const router = createRouter({
    routes,
    history:createWebHashHistory()
})
export default router
  1. main.js中配置
import { createApp } from 'vue'
import App from '@/App.vue'
import 'element-plus/dist/index.css'
import router from '@/router/index'
const app = createApp(App)
app.mount('#app')
app.use(router)

  1. axios二次封裝
import axios,{AxiosError, AxiosResponse, InternalAxiosRequestConfig} from 'axios';
const newAxios = axios.create({
    baseURL:'http://www.zhaijizhe.cn:3005',
    timeout:5000
})
newAxios.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
    const token = localStorage.getItem('token')
    if(token){
        config.headers.Authorization = token
    }
    return config
})
newAxios.interceptors.response.use((response:AxiosResponse)=>{
    return response
},(error:AxiosError)=>{
    return Promise.reject(error)
})
export default newAxios

請求的類型限制為:InternalAxiosRequestConfig
響應(yīng)的類型限制為:AxiosResponse

  1. 添加路由守衛(wèi)
router.beforeEach(async(to,from,next)=>{
    if(to.path == '/login'){
        next()
    }else{
        const token = localStorage.getItem('token')
        if(!token){
            ElMessage.warning('用戶未登錄,請登錄')
            next('/login')
        }else{
            try {
                await $api.user.getMenus()
                 dynamicRoute()
                next()
            } catch (error) {
                ElMessage.warning('token已失效,請重新登錄')
                next('/login')
            }
        }
    }
})

動(dòng)態(tài)路由搭建

  1. 定義路由的接口
export interface IUserMenu{
    _id:string,
    title:string,
    pid:string,
    path:string,
    icon:string,
    children:Array<IUserMenu>
}
export interface StateType{
    permissionList:Array<IUserMenu>
}

路由是數(shù)組所以定義為Array

  1. 安裝pinia
yarn add pinia
  1. 創(chuàng)建store的模塊
1. 導(dǎo)入defineStore
import {defineStore} from 'pinia'
2. 導(dǎo)入路由限定接口
import { stateType} from 'type地址'
3. 導(dǎo)入api
import $api from 'api地址'
4. 導(dǎo)入路由類型限制
import {RouteRecordRaw} from 'vue-router'
  - RouteRecordRaw是Vue Router v4.x中新增的一種路由配置類型,可以使得我們在編寫路由時(shí)更加方便靈活。它定義在@vue/router中,并且支持使用TypeScript類型推斷
5. 導(dǎo)入動(dòng)態(tài)獲取一組文件符合特定模式的模塊getViews方法
import {getViews} from '@/utils/getViews.ts'
6. 創(chuàng)建倉庫
const store = defineStore('auth',{
      state:():stateType=>{
        return {
          permissionList:[]
        }
      }
})
7. 根據(jù)action異步獲取菜單路由
actions:{
  async getAuthMenuAsync(){
    const result = await $api.user.getMenus()
    this.permissionList = result.data.data
  }
}
8. 通過getters獲取動(dòng)態(tài)路由
getters:{
  getHomeRoute(state:StateType){
    let homeRouteObj:RouteRecordRaw = {
      path:'/home',
       component:()=>import('../../views/HomePage.vue'),
      children:[]
    }
    // 定義一個(gè)數(shù)組用來存放子菜單的路由
    let arr:Array<RouteRecordRaw>=[]
   //  添加判斷解決首次進(jìn)入token失效,路由沒有跳轉(zhuǎn)的問題
    if(state&&state.permissionList){
            state.permissionList.forEach(item=>{
                if(item.children){
                    item.children.forEach(subItem=>{
                        let routeItem ={
                            path:subItem.path,
                            component:getViews((`../views${subItem.path}.vue`))
                        }
                        ary.push(routeItem)
                    })
                }
            })
           }
    // 將定義的數(shù)組賦值給路由對象中的子路由
    homRouteObj.children = arr
    return homRouteObj
  }
}

因?yàn)間etters可以直接獲取狀態(tài),action主要是用于異步操作和業(yè)務(wù)邏輯的處理

  1. 安裝pinia持久化插件
yarn add pinia-plugin-persist
  • 在store的user模塊中配置persist
const useAuthStore = defineStore('auth', {
    state: (): StateType => { },
    getters:{},
    actions:{},
    persist:{
        enabled:true,
        strategies:[
            {
                key:'userAuth',
                storage:localStorage
            }
        ]
    }
})

這時(shí)會(huì)報(bào)錯(cuò),需要在tsconfig.json中將 “moduleResolution”: “node”,改為node

  • 在倉庫的入口文件中配置插件
import {createPinia} from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPluginPersist)
export default pinia
  1. 在utils文件中創(chuàng)建動(dòng)態(tài)路由添加的方法
1. 導(dǎo)入useAuthStore倉庫
import useAuthStore from '@/store/modules/user'
2. 導(dǎo)入路由
import router from '@/router/index'
3. 編寫方法
 const dynamicRoute = ()=>{
    const store = useAuthStore()
    - 將異步獲取菜單權(quán)限的方法結(jié)構(gòu)出來
    const {getAuthMenuAsync} = store
    - 調(diào)用異步方法
    getAuthMenuAsync()
    - 調(diào)用獲取路由的方法
    const homeRoute= store.getDynicRoute
    - 將獲取的路由添加到路由
    router.addRoute(homeRoute)
}
  1. 在utils文件中創(chuàng)建動(dòng)態(tài)獲取Component的方法
export const getViews(path:string){
   let modules = import.meta.glob('../**/*.vue')
   return modules[path]
}

import.meta.glob是ES2020的一個(gè)新特性,用于動(dòng)態(tài)獲取一組文件符合特定模式的模塊,返回一個(gè)鍵/值對象形式的Promise??梢允褂胕mport.meta.glob將所有以.vue結(jié)尾的文件導(dǎo)入為模塊,并且可以使用for…in循環(huán)遍歷得到每個(gè)匹配到的路徑,再通過動(dòng)態(tài)導(dǎo)入對應(yīng)的組件進(jìn)行處理。

  1. 在路由守衛(wèi)中調(diào)用utils中動(dòng)態(tài)獲取路由的方法
1. 導(dǎo)入動(dòng)態(tài)獲取路由的方法
import dynamicRoute from '@/utils/dynicRoute'
2. 導(dǎo)入路由的限制類型
import {RouteRecordRaw,createRouter,createWebHistory} from 'vue-router'
3. 導(dǎo)入api
import $api from '@/api/index'
4. 導(dǎo)入elmessage
import { ElMessage } from 'element-plus'
5. 導(dǎo)入動(dòng)態(tài)路由
import dynamicRoute from '@/utils/dynicRoute'
6. 創(chuàng)建路由表
const routes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        component: () => import('@/views/Login.vue')
    },
    - 設(shè)置路由重定向
    {
        path: '/',
        redirect: '/home'
    }
]
7. 創(chuàng)建路由
const router = createRouter({
    history: createWebHistory(),
    routes
})
8. 添加路由守衛(wèi)
router.beforeEach(async (to, _, next) => {
    if (to.path == '/login') {
        next()
    } else {
        const token = localStorage.getItem('token')
        if (!token) {
            ElMessage.warning('用戶未登錄,請登錄')
            next('/login')
        } else {
            try {
                await $api.user.getMenus()
                - 調(diào)用動(dòng)態(tài)獲取路由的方法
                dynamicRoute()
                next()
            } catch (error) {
                ElMessage.warning('token已失效,請重新登錄')
                next('/login')
            }
        }
    }
})
9. 導(dǎo)出路由
export default router

創(chuàng)建菜單組件

  1. 創(chuàng)建路由限制接口 IUserMenu
export interface IUserMenu{
    _id:string,
    title:string,
    pid:string,
    path:string,
    icon:string,
    children:Array<IUserMenu>
}
  1. 導(dǎo)入Mounted生命周期和ref
import { onMounted,red} from 'vue'
  1. 導(dǎo)入Api
import $api from 'api地址'
  1. 聲明Menus數(shù)據(jù)變量
const Menus = ref<Array<IUserMenu>>([])
  1. 創(chuàng)建動(dòng)態(tài)獲取用戶菜單
const getMenus = async () => {
    const result = await $api.user.getMenus()
    Menus.value = result.data.data
    dynamicRoute()
}
  1. 掛載方法
onMounted(() => {
    getMenus()
})
  1. 菜單的模板
  • 如果要讓elementplus的menu菜單啟用vu-router路由模式,需要在el-menu標(biāo)簽中設(shè)置:router=“true”
- 在Home的el-main區(qū)域內(nèi)容配置二級路由出口
<template>
    <div>
        <el-menu :router="true" class="elMenu" background-color="#545c64">
            <el-sub-menu v-for="item in Menus" :key="item._id" :index="item._id">
                <template #title>
                    <el-icon>
                        <component :is="item.icon"></component>
                    </el-icon>
                    <span>{{ item.title }}</span>
                </template>
                <el-menu-item v-for="subItem in item.children" :key="subItem._id" :index="subItem.path">
                    <template #title>
                        <span>{{ subItem.title }}</span>
                    </template>
                </el-menu-item>
            </el-sub-menu>
        </el-menu>
    </div>
</template>

其中渲染icons圖標(biāo)使用動(dòng)態(tài)組件component, #title是v-slot的縮寫

main.js中進(jìn)行路由的配置

  1. 導(dǎo)入createApp和App組件
import { createApp } from 'vue'
import App from '@/App.vue'
  1. 導(dǎo)入路由
import router from '@/router/index'
  1. 導(dǎo)入Element相關(guān)配置
import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus'
- 導(dǎo)入element中的icon
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  1. 導(dǎo)入動(dòng)態(tài)獲取路由的方法
import dynamicRoute from '@/utils/dynicRoute'
  1. 導(dǎo)入倉庫入庫文件
import pinia from '@/store'
  1. 使用pinia,ElementPlus,router并且掛載app
const app = createApp(App)
// 循環(huán)遍歷elementUI的icon
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.use(pinia)
app.use(ElementPlus)
dynamicRoute()
app.use(router)
app.mount('#app')

一定要注意動(dòng)態(tài)路由的添加必須放在app.use(router)之前,app.use(pinia)之后文章來源地址http://www.zghlxwxcb.cn/news/detail-448954.html

到了這里,關(guān)于Vue3添加動(dòng)態(tài)路由及項(xiàng)目搭建的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • vue-create 創(chuàng)建 VUE3項(xiàng)目-創(chuàng)建

    vue-create 創(chuàng)建 VUE3項(xiàng)目-創(chuàng)建

    1.創(chuàng)建文件夾右鍵點(diǎn)擊打開終端或目錄cmd ?2.輸入命令 vue create (這里跟的是項(xiàng)目的名稱 不能為或帶中文) ?3.選中第三個(gè)類別自定義創(chuàng)建項(xiàng)目? ? ? ? ? ? ? //? ?或者選擇第一個(gè)快捷創(chuàng)建VUE3 進(jìn)入第12步 4.我們可以按上下鍵,然后按空格鍵選中需要的選項(xiàng),最后按回車

    2024年02月03日
    瀏覽(23)
  • 【前端Vue】Vue3+Pinia小兔鮮電商項(xiàng)目第4篇:靜態(tài)結(jié)構(gòu)搭建和路由配置,1. 準(zhǔn)備分類組件【附代碼文檔】

    【前端Vue】Vue3+Pinia小兔鮮電商項(xiàng)目第4篇:靜態(tài)結(jié)構(gòu)搭建和路由配置,1. 準(zhǔn)備分類組件【附代碼文檔】

    Vue3+ElementPlus+Pinia開發(fā)小兔鮮電商項(xiàng)目完整教程(附代碼資料)主要內(nèi)容講述:認(rèn)識(shí)Vue3,使用create-vue搭建Vue3項(xiàng)目1. Vue3組合式API體驗(yàn),2. Vue3更多的優(yōu)勢,1. 認(rèn)識(shí)create-vue,2. 使用create-vue創(chuàng)建項(xiàng)目,1. setup選項(xiàng)的寫法和執(zhí)行時(shí)機(jī),2. setup中寫代碼的特點(diǎn)。什么是pinia,創(chuàng)建空Vue項(xiàng)目并安裝

    2024年04月11日
    瀏覽(28)
  • 【vue create】一.使用vue creat搭建項(xiàng)目

    【vue create】一.使用vue creat搭建項(xiàng)目

    場景 :使用vue create腳手架快速搭建vue的項(xiàng)目 前提 :需要安裝node.js和cnpm以及yarn 并且cnpm需要設(shè)置為淘寶鏡像,cnpm和yarn安裝教程網(wǎng)上很多可以自行搜索 查看安裝的版本(顯示版本號(hào)說明安裝成功) 1.cmd窗口跳到需要新建項(xiàng)目的文件夾下,使用vue create 2.我這里選擇第三個(gè)Ma

    2024年02月06日
    瀏覽(19)
  • 基于vscode實(shí)現(xiàn)vue3項(xiàng)目創(chuàng)建啟動(dòng)+安裝配置路由vue-router實(shí)現(xiàn)單頁面組件切換

    基于vscode實(shí)現(xiàn)vue3項(xiàng)目創(chuàng)建啟動(dòng)+安裝配置路由vue-router實(shí)現(xiàn)單頁面組件切換

    訪問https://nodejs.org/en,點(diǎn)擊下載最新版本的nodejs,并安裝。 在項(xiàng)目目錄文件下,通過cmd運(yùn)行下述指令。 依次輸入下列命令,啟動(dòng)vue項(xiàng)目 在瀏覽器中加載http://localhost:5173/,頁面加載成功,說明vue項(xiàng)目安裝啟動(dòng)成功。 建議安裝第三方庫通過vscode中的終端來操作,項(xiàng)目啟動(dòng)通過

    2024年02月03日
    瀏覽(97)
  • Vue-根據(jù)角色獲取菜單動(dòng)態(tài)添加路由

    Vue-根據(jù)角色獲取菜單動(dòng)態(tài)添加路由

    如果大家寫過后臺(tái)管理系統(tǒng)的項(xiàng)目,那么動(dòng)態(tài)路由一定是繞不開的,如果想偷懶的話,就把所有路由一開始都配置好,然后只根據(jù)后端返回的菜單列表渲染就好菜單就好了,但是這樣的隱患就是我在地址欄輸入的地址的時(shí)候,也會(huì)進(jìn)入這個(gè)頁面,不偷懶的方法就是本文要介紹

    2024年01月24日
    瀏覽(23)
  • Vue3+Vite+Pinia+Naive項(xiàng)目搭建之二:scss 的安裝和使用

    Vue3+Vite+Pinia+Naive項(xiàng)目搭建之二:scss 的安裝和使用

    前言 如果對 vue3 的語法不熟悉的,可以移步?Vue3.0 基礎(chǔ)入門,快速入門。 github 開源庫:Vue3-Vite-Pinia-Naive-Js gitee? ?開源庫:Vue3-Vite-Pinia-Naive-Js 1. 安裝依賴 ?2. 新增 src/assets/style/reset.scss?頁面樣式初始化 3. 新增 src/assets/style/common.scss?共用樣式 4. 新增 src/assets/style/utils.scss?工

    2024年02月12日
    瀏覽(19)
  • Vue2中根據(jù)權(quán)限添加動(dòng)態(tài)路由

    Vue2中根據(jù)權(quán)限添加動(dòng)態(tài)路由

    大概記錄一下主要代碼 大概結(jié)構(gòu)如下:

    2024年02月12日
    瀏覽(30)
  • vue實(shí)現(xiàn)動(dòng)態(tài)路由添加(簡單無廢話版本)

    最近練習(xí)vue的項(xiàng)目,有關(guān)于后臺(tái)管理系統(tǒng)的動(dòng)態(tài)添加路由部分,根據(jù)思路實(shí)現(xiàn)了基本的功能,在這里記錄一下,等后面學(xué)習(xí)后在進(jìn)行優(yōu)化。 這里只是記錄我個(gè)人最后實(shí)現(xiàn)的思路,本人由于是初學(xué)者,可能思路和代碼有不正確地方,還求多見諒。也請能不吝賜教,一同進(jìn)步。 我

    2023年04月08日
    瀏覽(21)
  • Vue3動(dòng)態(tài)路由(Vite+Vue3+TS+Mock)

    Vue3動(dòng)態(tài)路由(Vite+Vue3+TS+Mock)

    Vue通過路由進(jìn)行頁面管理,不同的路由綁定到不同的頁面。一般來說,前端直接寫好的路由為靜態(tài)路由,在不修改代碼的情況下,路由表是不會(huì)改變的。對于不需要?jiǎng)討B(tài)改變路由表的網(wǎng)站,靜態(tài)路由就已經(jīng)足夠了,但是當(dāng)頁面需要與權(quán)限進(jìn)行綁定時(shí),不同用戶允許瀏覽的頁面

    2024年02月02日
    瀏覽(25)
  • vue3實(shí)現(xiàn)動(dòng)態(tài)菜單和動(dòng)態(tài)路由和刷新后白屏處理

    vue3實(shí)現(xiàn)動(dòng)態(tài)菜單和動(dòng)態(tài)路由和刷新后白屏處理

    項(xiàng)目中,當(dāng)每一個(gè)角色得到的界面不一致的時(shí)候,我們就不能使用靜態(tài)菜單了,而是要從后端得到動(dòng)態(tài)的菜單數(shù)據(jù),然后動(dòng)態(tài)的將菜單數(shù)據(jù)展示在界面上。 除了在界面展示,也還要將界面的路由動(dòng)態(tài)添加,在路由動(dòng)態(tài)添加之后,你可能會(huì)出現(xiàn)刷新界面,界面變白的情況,頁面

    2024年02月06日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包