跳到主要内容

如何在Vue3 ts项目中使用 Vue Route

Prerequisite

  1. 安装Nodejs, 官网地址,推荐版本16.xxx18.xxx ;
  2. 安装pnpm,按照以下命令安装:npm install -g pnpm
  3. 创建一个vite vue3 ts项目,使用pnpm create vite-app my-vue3-ts-project
  4. 安装编辑器工具,推荐使用VS Code,可从 visualstudio 下载。

Preview Project Structure

Project Construction

Install dependencies

pnpm install vue-router4.2.5
pm install @vitejs/plugin-vue@5.0.2 -D
pnpm install @types/node20.10.6 -D
pm install @vue/ts config -D

pnpm install vue-router@4.2.5

此命令安装Vue Router包的版本为4.2.5。Vue Router是用于Vue.js应用程序的库,它使得在不同组件之间导航、管理应用程序的URL以及提供导航历史变得更加容易。

pnpm install @vitejs/plugin-vue@5.0.2 -D

此命令安装Vue.js的Vite插件,版本为5.0.2。Vite是一个专为Vue.js优化的现代Web开发构建工具。此插件特别将Vue.js与Vite集成,允许在Vite项目中使用Vue组件。

pnpm install @types/node@20.10.6 -D

此命令安装Node.js的TypeScript类型定义,版本为20.10.6。在使用TypeScript时,为您使用的库定义类型是非常重要的,@types/node包为Node.js提供了这些定义。

pnpm install @vue/tsconfig -D

此命令安装Vue.js TypeScript配置包。@vue/tsconfig包为Vue.js项目提供了默认的TypeScript配置。它包含了在Vue开发中常用且推荐使用的设置。 该配置在项目的tsconfig.json文件中通过"extents"属性被引用。

tsconfig.json

{
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
// this to solve some error hints
"ignoreDeprecations": "5.0",
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"]
},

"vueCompilerOptions": {
"nativeTags": ["block", "component", "template", "slot"]
},

"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

vite.config.mts

// vite.config.mts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
resolve:{
alias:{
'@': path.resolve(__dirname, 'src')
}
},
plugins: [vue()]
});

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './route/index.ts';

createApp(App).use(router).mount('#app')

这段代码设置了一个 Vue. 带有根组件(App)的应用程序,使用 Vue Router 插件进行导航,并将整个应用程序挂载到 ID 为“app”的 HTML 元素。 这是 Vue 的常见设置。 单页应用程序,其中路由由 Vue Router 管理,并且应用程序安装到特定的 DOM 元素。

App.vue

<!-- App.vue -->
<template>
<div id="app">
<router-view></router-view>
</div>
</template>

route.ts

// router.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'home',
component: () => import('@/views/MyPage.vue'),
meta: {
title: 'Home',
},
},
]

const router = createRouter({
history: createWebHistory(),
routes,
})

export default router

MyPage.vue

<template>
<view>
<input type="text" v-model="inputText" />
</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const inputText = ref<string>('hello')
</script>

Visit

运行pnpm dev,在浏览器中访问localhost:5173

visited Page

Conclusion

为了防止命令的拼写错误,建议直接复制指令并粘贴到您的VS Code中。您可以从 GitHub 存储库 下载代码。

感谢您花费宝贵的时间来阅读文章。如果您觉得我的文章有用,请给予一点肯定。同时,随时提出您可能有的任何问题。