引入vue-router
npm install vue-router@next --save
在src目录下创建router文件夹,在文件夹下创建index.ts
import {createRouter, RouteRecordRaw, Router, createWebHistory} from 'vue-router' const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: () => import('@/views/Home.vue'), meta: { title: '首页' } } ] const router: Router = createRouter({ history: createWebHistory(), routes }) export default router
创建 views/Home.vue
<template> <HelloWorld :msg="msg"></HelloWorld> </template> <script lang="ts"> import HelloWorld from "@/components/HelloWorld.vue" import { defineComponent } from "vue" export default defineComponent({ name: "Home", components: { HelloWorld }, setup() { return { msg: "hello World", } } }) </script>
在main.ts中引入router
import {createApp} from 'vue' import router from './router/index' import App from './App.vue' createApp(App).use(router).mount('#app')
将App.vue中内容替换
<template> <img alt="Vue logo" src="./assets/logo.png" /> <router-view /> </template> <script> export default { name: 'App', setup() { } } </script>
运行报错如下,router找不到路径
下午11:42:12 [vite] Internal server error: Failed to resolve import "@/views/Home.vue" from "src\router\index.ts". Does the file exist? Plugin: vite:import-analysis File: D:/workspace/test/element-plus-ts/src/router/index.ts 4 | path: "/home", 5 | name: "Home", 6 | component: () => import("@/views/Home.vue"),
那么需要修改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') } } })
安装 path模块
npm install --save-dev @types/node
配置完成,运行
npm run dev