Vue3官网:https://v3.cn.vuejs.org/
Vite官网:https://cn.vitejs.dev/
VueRouter官网:https://next.router.vuejs.org/zh/
使用Vite构建时,会和以前的有些写法有些不同,例如之前我们使用
// 导入路由对象
import VueRouter from 'vue-router'
// 路径配置 .vue 可以省略
const routes = [
{
path: '/',
name: 'index',
component: () => import('@/pages/index') //.vue可以省略
}
]
现在使用:
// 导入路由对象
import { createRouter,createWebHistory } from 'vue-router'
// 路径配置 .vue 不可省略
const routes = [
{
path: '/',
name: 'index',
component: () => import('@/pages/index.vue') //.vue不可省略
}
]
以下是详细步骤
1、安装路由 Vue Router
npm install vue-router@4
2、配置路由文件(建立路由js)
在src目录下新建目录叫“router”,新建一个js文件叫“index.js”,文件内容如下:
// 导入router所需的方法
import { createRouter, createWebHistory } from 'vue-router'
// 导入路由页面的配置
import routes from './routes'
// 路由参数配置
const router = createRouter({
// 使用hash(createWebHashHistory)模式,(createWebHistory是HTML5历史模式,支持SEO)
history: createWebHistory(),
routes: routes,
})
// 全局前置守卫,这里可以加入用户登录判断
router.beforeEach((to, from, next) => {
// 继续前进 next()
// 返回 false 以取消导航
next()
})
// 全局后置钩子,这里可以加入改变页面标题等操作
router.afterEach((to, from) => {
const _title = to.meta.title
if (_title) {
window.document.title = _title
}
})
// 导出默认值
export default router
接着新建一个js文件叫“routes”,内容如下(可以自己继续添加其他页面):
const routes = [
{
path: '/',
name: 'index',
title: '首页',
component: () => import('@/components/index.vue'), //.vue不能省略
}
]
export default routes
3、在main.js中使用路由
在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')
4、修改Vite的配置文件,支持alias别名@
打开vite.config.js,如果你的path出现了红色波浪线,则还需要安装 @types/node
npm install --save @types/node
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
}
},
plugins: [vue()]
})