Vue3使用路由及配置vite.alias简化导入写法的过程详解
作者:曲鸟
这篇文章主要介绍了Vue3使用路由及配置vite.alias简化导入写法,本文通过实例代码给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、使用路由
1)安装vue-router
yarn add vue-router
2)注册路由
将两个组件Home、Project注册到路由中:
import { createApp } from "vue";
import { createRouter, createWebHashHistory } from 'vue-router';
import App from "./App.vue";
const Home = { render(){ return 'Home'} }
const Project = { render(){ return 'Project'} }
const routes = [
{ path: '/', component: Home },
{ path: '/project', component: Project },
]
const app = createApp(App);
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
});
app.use(router);
app.mount("#app");3)使用路由
App.vue文件加入如下代码:
<template> <router-view></router-view> </template>
效果如下:


二、配置vite.alias简化导入写法
1)安装@types/node
yarn add @types/node
2)修改vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
}
}
})3)修改tsconfig.JSON (不修改没有提示)
在compilerOptions中加入下面配置:
"baseUrl": "./",
"paths": {
"@/*": ["./src/*"] //格式一定要写对符号*不能少不然找不到@或者没有代码提示
},
效果如下:

到此这篇关于Vue3使用路由及配置vite.alias简化导入写法的文章就介绍到这了,更多相关vue3 vite.alias路由配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
