2022-11-04

在vite+vue3+ts項(xiàng)目下,實(shí)現(xiàn)根據(jù)文件名稱自動(dòng)生成路由

1、安裝插件

npm install vite-plugin-pages -D
npm install vue-router

2、在vite.config.ts中完成vite-plugin-pages 的配置
pages為放置vue頁面的文件夾名稱

import Pages from 'vite-plugin-pages'
export default defineConfig({
  plugins: [
    vue(),
    /**根據(jù)文件名自動(dòng)生成對應(yīng)路由 @see https://github.com/hannoeru/vite-plugin-pages*/ 
    Pages({
      dirs: [
        {dir: 'src/pages', baseRoute: ''},
        {dir: 'src/pages/active', baseRoute: 'active'},
      ],
      exclude: ['**/components/*.vue'],
    })
)}

3、在main.ts中創(chuàng)建一個(gè)router,并讓 app use

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import './style.css'
import routes from 'pages-generated' // vite-plugin-pages 生成的路由信息
import App from './App.vue'
const router = createRouter({
  history: createWebHistory(),
  routes
})
const app = createApp(App)
app.use(router).mount('#app')

4、在App.vue中添加router-view

<template>
  <router-view />
</template>

5、添加測試頁面

<!-- pages/index.vue -->
<template>
  <div>Hello, Vite</div>
</template>

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

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

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