- 安装路由 Vue Router
npm install vue-router@4
- 配置路由文件:src/router/index.js(建立路由js)
import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
- 新建一个js文件叫“routes”,内容如下(可以自己继续添加其他页面):
const routes = [
{
path: '/',
name: 'index',
title: '首页',
component: () => import('@/components/index.vue'),
}
]
export default routes
- 在main.js中使用路由
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
const app = createApp(App)
app.use(router)
app.mount('#app')
- 修改Vite的配置文件,支持alias别名@
import { defineConfig } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
}
},
plugins: [vue()]
})