1.vite项目搭建
可以按照vite官网操作:https://cn.vitejs.dev/guide/features.html#typescript
npm create vite@latest
自定义template模板
vscode-文件-首选项-配置用户代码片段-vue.json
添加如下代码即可快速创建vue模板
{
"template": {
"prefix": "vue",
"body": [
"<template></template>",
"<script setup lang='ts'></script>",
"<style scoped lang='less'></style>"
]
}
}
element ui
element官网:https://element-plus.gitee.io/zh-CN/guide/design.html
npm install element-plus --save
// main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
Volar支持,请在 tsconfig.json 中通过 compilerOptions.type 指定全局组件类型。
// tsconfig.json
{
"compilerOptions": {
// ...
"types": ["element-plus/global"]
}
}
配置@别名
vite.config.ts compilerOptions
中配置如下
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["./src/components/*"]
},
安装 path 和 @types/node
npm install path --save
npm install @types/node --save-dev
vite.config.ts 配置如下
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
// 配置路径别名
alias: {
"@": path.resolve(__dirname, "./src"),
"@components": path.resolve(__dirname, "./src/components"),
},
},
plugins: [vue()],
});
配置路由
npm i vue-router@4
在src根目录创建router文件夹并新建两个ts文件,index.ts、router.ts
router.ts
const routes = [
{
name: "Home",
path: "/",
component: () => import("@/pages/Home.vue"),
},
{
name: "About",
path: "/about",
component: () => import("@/pages/About.vue"),
},
{
name: "Apple",
path: "/apple",
component: () => import("@/components/Apple/Apple.vue"),
},
];
export default routes; //导出
index.ts
import { createRouter, createWebHistory } from "vue-router";
import routes from "./router";
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
将vite自动创建的页面删除,并在app.vue增加router-view视图出口
app.vue
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
</script>
<template>
<router-view></router-view>
</template>
<style scoped>
</style>
在home首页配置一个跳转的函数
<template>
<div>home首页</div>
<el-button type="primary" @click="toApp" plain>跳转到apple</el-button>
<A></A>
</template>
<script setup lang="ts">
import { useRouter } from "vue-router";
import A from "../components/Apple/A.vue";
const route = useRouter();
const toApp = () => {
route.push({ name: "Apple" });
};
</script>
<style scoped lang="less"></style>
现在就可以看到配置的路由效果了: