使用Vite构建Vue3项目,对路由Vue Router 4.x的设置

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()]
})
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值