1.安装
yarn add vue-router@4
2. 配置相关
① 配置别名
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
find: '@',
replacement: path.resolve('./src')
}
]
},
base:'./', //设置打包路径
// server: {
// host: "localhost",
// port: 3000,
// https: true
// },
})
如果是刚创建的typeScript项目,会出现报错提示"找不到模块path或相应的类型声明",所以需要安装@types/[node]
yarn add @types/node
typeScrip 配置别名后 stsconfig.json 需要添加 baseUrl path 配置 不然使用别名@会提示找不到
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
3. 路由配置文件
// 在src目录下添加router/index.ts文件,并配置
import { createRouter, createWebHashHistory } from "vue-router";
import Home from '../views/Home.vue'
const router = createRouter({
history: createWebHashHistory(),
routes: [{
path: '/',
name: 'home',
component: Home,
},
{
path: '/about',
name: 'About',
//路由懒加载
component: () => import('../views/About.vue')
}
]
})
export default router
4.mian.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from '@/router/index'
createApp(App).use(router).mount('#app')
5.App.vue
<template>
<router-view></router-view>
</template>