技術(shù)選擇:vue3晋辆,vite,ts宇整,less瓶佳,pinia,axios没陡,npm涩哟,node
前言:vue3開始推薦使用vite來構(gòu)建項目,速度更快盼玄,而vue-cli維護了贴彼,ts來檢查代碼規(guī)范,css預編譯推薦使用less,因為很多組件都是用less來寫的埃儿,兼容性更好器仗,pinia是作者尤雨溪推薦的新一代狀態(tài)管理工具,更兼容v3+ts語法童番,后面大概率pinia會代替vuex的精钮,pinia的寫法更為簡化。
1.vite創(chuàng)建Vue3項目
創(chuàng)建命令:
npm create vite@latest
填寫項目名:
Project name: >> vite-vue3-ts-demo
選擇vue:
√ Project name: ... vite-vue3-ts-demo
? Select a framework: ? - Use arrow-keys. Return to submit.
Vanilla
> Vue
React
Preact
Lit
Svelte
Others
選擇ts:
? Select a variant: ? - Use arrow-keys. Return to submit.
JavaScript
> TypeScript
Customize with create-vue
Nuxt
創(chuàng)建完成剃斧,可以根據(jù)地址直接找到目標項目轨香,丟到vscode中,然后安裝依賴:
Scaffolding project in C:\Users\Administrator\vite-vue3-ts-demo...
Done. Now run:
cd vite-vue3-ts-demo
npm install
npm run dev
2.安裝依賴幼东,配合路由和一些基礎(chǔ)配置
先安裝2個插件volar
插件下載
配置@別名
- 先添加一個依賴防止報錯
npm i @types/node
- vite.config.js添加配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve:{
alias:{
"@": resolve(__dirname,"./src")
}
}
})
tsconfig.json添加配置
{
"compilerOptions": {
"target": "ESNext",
···
// 配置@別名
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
},
}
安裝less
npm i -d less
安裝 vue-router
npm i vue-router@4
main.ts文件引入router(此時發(fā)現(xiàn)@后面沒有提示臂容,需要加個插件Path-intellisense科雳,并配置)
步驟1
步驟2
配置如下
{
//添加以下配置(主要是前兩個)
"path-intellisense.mappings": {
"@/": "${workspaceFolder}/src",
"/": "${workspaceFolder}",
"lib": "${workspaceFolder}/lib",
"global": "/Users/dummy/globalLibs"
},
"path-intellisense.autoTriggerNextSuggestion": true
}
提示就出來了
不需輸入首字母提示成功顯示
在src下創(chuàng)建一個 routes 文件夾,再創(chuàng)建一個 index.ts 文件
import {createRouter,createWebHistory} from "vue-router"
let routes = [
{
path:"/",
name:"home",
component:() => import("@/pages/home.vue")
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
main.ts引入成功
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from '@/routes/index'
createApp(App).use(router).mount('#app')
修改App.vue文件(Vue3/Vue Router4下使用Keep-alive)
<template>
<router-view v-slot="{ Component }">
<keep-alive :include="includeList">
<component :is="Component"></component>
</keep-alive>
</router-view>
</template>
<script lang="ts">
//使用動態(tài)include解析
export default {
name: 'App',
data(){
return {
includeList : []
}
},
watch:{
$route(to:any) {
//監(jiān)聽路由變化脓杉,把配置路由中keepAlive為true的name添加到include動態(tài)數(shù)組中
const that:any = this;
if(to.meta.keepAlive && that.includeList.indexOf(to.name) === -1){
that.includeList.push(to.name);
}
}
}
}
</script>
運行項目糟秘,正常顯示
npm run dev