Vue3使用路由及配置vite.alias簡化導入寫法的過程詳解
更新時間:2022年11月11日 09:26:25 作者:曲鳥
這篇文章主要介紹了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 模式的實現(xiàn)。為了簡單起見,我們在這里使用 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路由配置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

