自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vite+Vue2+Composition-api+<script setup>+TypeScript搭配如何開發(fā)項目?

開發(fā) 項目管理
我們在搭建Vite項目,選擇Vue模板之后,默認(rèn)會下載Vue3模板。如果你的公司現(xiàn)在還沒有準(zhǔn)備使用Vue3,而在使用Vue2,那么這篇文章值得你繼續(xù)看下去。

  [[425600]]

前言

Vite相信大家都用過,它是一種新型前端開發(fā)與構(gòu)建工具,能夠顯著提升前端開發(fā)體驗。我們在搭建Vite項目,選擇Vue模板之后,默認(rèn)會下載Vue3模板。如果你的公司現(xiàn)在還沒有準(zhǔn)備使用Vue3,而在使用Vue2,那么這篇文章值得你繼續(xù)看下去。下面,我將帶大家如何搭建一個 Vite+Vue2+Composition-api+<script setup>+TypeScript  搭配使用的項目。這篇文章很干,請大家點點贊哦!

安裝所需依賴

又到了實戰(zhàn)環(huán)節(jié),下面可以一步步跟著我哦!我這里使用的是yarn 依賴管理工具。

初始化項目

這里使用快捷初始化命令:

  1. yarn init -y 

創(chuàng)建完package.json文件之后,我們可以手動修改下項目名稱字段name:vitevue2p。

初始化Vite

安裝Vite。

  1. yarn add vite -D 

初始化Vue2

我們需要安裝Vue2,所以直接這樣安裝。

  1. yarn add vue 

目前,我安裝的版本是^2.6.14。

另外,我們還需要安裝vue-template-compiler這個依賴,此包可用于將Vue 2.0模板預(yù)編譯為渲染函數(shù),以避免運行時編譯開銷和CSP限制。在編寫具有非常特定需求的構(gòu)建工具時,才需要單獨使用它。所以,我們這里單獨安裝。

  1. yarn add vue-template-compiler -D 

最后,如果想讓Vite支持Vue2,就必須安裝這個依賴vite-plugin-vue2。

  1. yarn add vite-plugin-vue2 -D 

支持Composition-api

Composition-api字面意思是組合API,它是為了實現(xiàn)基于函數(shù)的邏輯復(fù)用機制而產(chǎn)生的。這也是Vue3亮點之一,那么我們?nèi)绾尾拍軌蛟赩ue2項目中使用呢?這需要安裝@vue/composition-api依賴。

  1. yarn add @vue/composition-api 

支持<script setup>語法

<script setup>是在單文件組件 (SFC) 中使用組合式 API 的編譯時語法糖,是Vue3.2新加入的語法。那么,我們也可以在Vue2項目中使用它。

你需要安裝unplugin-vue2-script-setup依賴。

  1. yarn add unplugin-vue2-script-setup -D 

了解更多,可以查看https://github.com/antfu/unplugin-vue2-script-setup。

在Vue2項目中使用Volar

以下是官方的解釋:

我們建議將 VS Code 與 Volar 結(jié)合使用以獲得最佳體驗(如果您擁有 Vetur,您可能希望禁用它)。使用 Volar 時,您需要安裝 @vue/runtime-dom 作為 devDependencies 以使其在 Vue 2 上工作。

  1. yarn add @vue/runtime-dom -D 

支持TypeScript語法

隨著應(yīng)用的增長,靜態(tài)類型系統(tǒng)可以幫助防止許多潛在的運行時錯誤,所以我們推薦使用TypeScript。

  1. yarn add typescript -D 

最后,我把安裝的所有依賴列出來,可以參照有沒有漏的。

  1. "dependencies": { 
  2.   "@vue/composition-api""^1.1.5"
  3.   "vue""^2.6.14" 
  4. }, 
  5. "devDependencies": { 
  6.   "@vue/runtime-dom""^3.2.11"
  7.   "typescript""^4.4.3"
  8.   "unplugin-vue2-script-setup""^0.6.4"
  9.   "vite""^2.5.7"
  10.   "vite-plugin-vue2""^1.8.1"
  11.   "vue-template-compiler""^2.6.14" 

搭建項目架構(gòu)

首先,我先列出我自己搭建的項目文件目錄,我是參照Vite默認(rèn)模板而創(chuàng)建的文件目錄。

  1. public 
  2.   -- favicon.ico 
  3. - src 
  4.   -- assets 
  5.     --- logo.png 
  6.   -- components 
  7.     --- Async.vue 
  8.     --- Bar.vue 
  9.     --- Foo.vue 
  10.     --- HelloWorld.vue 
  11.   -- App.vue 
  12.   -- main.ts 
  13.   -- shims-vue.d.ts 
  14. index.html 
  15. - package.json 
  16. - ref-macros.d.ts 
  17. - tsconfig.json 
  18. - vite.config.ts 

下面,我們按排列順序分別看下文件中都放了什么東西?

public文件夾中放著一個ico圖標(biāo)文件,這個不再說明。src文件夾中文件有點多,我們放在最后討論。

index.html

談到index.html這個文件,我們需要引入Vite官網(wǎng)一段話:

你可能已經(jīng)注意到,在一個 Vite 項目中,index.html 在項目最外層而不是在 public 文件夾內(nèi)。這是有意而為之的:在開發(fā)期間 Vite 是一個服務(wù)器,而 index.html 是該 Vite 項目的入口文件。

Vite 將 index.html 視為源碼和模塊圖的一部分。Vite 解析 <script type="module" src="..."> ,這個標(biāo)簽指向你的 JavaScript 源碼。甚至內(nèi)聯(lián)引入 JavaScript 的 <script type="module"> 和引用 CSS 的 <link href> 也能利用 Vite 特有的功能被解析。另外,index.html 中的 URL 將被自動轉(zhuǎn)換,因此不再需要 %PUBLIC_URL% 占位符了。

  1. <!DOCTYPE html> 
  2. <html lang="en"
  3.  
  4. <head> 
  5.   <meta charset="UTF-8"
  6.   <link rel="icon" href="/favicon.ico" /> 
  7.   <meta name="viewport" content="width=device-width, initial-scale=1.0"
  8.   <title>Vite App</title> 
  9. </head> 
  10.  
  11. <body> 
  12.   <div id="app"></div> 
  13.   <script type="module" src="/src/main.ts"></script> 
  14. </body> 
  15.  
  16. </html> 

package.json

這個文件定義了這個項目所需要的各種模塊,以及項目的配置信息(比如名稱、版本、許可證等元數(shù)據(jù))。這里,需要注意的是我們自定義了"scripts"字段,有三個命令:"vite --open"、"vite preview"、"vite build"。

  1.   "name""vitevue2p"
  2.   "version""0.1.1"
  3.   "description"""
  4.   "keywords": [], 
  5.   "license""MIT"
  6.   "main""dist/index.js"
  7.   "module""dist/index.mjs"
  8.   "scripts": { 
  9.     "dev""vite --open"
  10.     "serve""vite preview"
  11.     "build""vite build" 
  12.   }, 
  13.   "dependencies": { 
  14.     "@vue/composition-api""^1.1.5"
  15.     "vue""^2.6.14" 
  16.   }, 
  17.   "devDependencies": { 
  18.     "@vue/runtime-dom""3.2.11"
  19.     "typescript""^4.4.3"
  20.     "unplugin-vue2-script-setup""^0.6.4"
  21.     "vite""^2.5.7"
  22.     "vite-plugin-vue2""^1.8.1"
  23.     "vue-template-compiler""^2.6.14" 
  24.   } 

ref-macros.d.ts

以d.ts后綴結(jié)尾的是TypeScript中的類型定義文件。我們知道自從引入 Composition API 以來,一個主要未解決的問題是 refs 與reactive的使用,到處使用 .value可能很麻煩,如果不使用類型系統(tǒng),很容易錯過。一些用戶特別傾向于只使用reactive,這樣他們就不必處理refs。

為了優(yōu)化,官方提出了一個RFC,大家可以打開下面這個網(wǎng)址 https://github.com/vuejs/rfcs/discussions/369 了解一下。

下面,可以看下一個簡單的例子。

  1. // declaring a reactive variable backed by an underlying ref 
  2. let count = $ref(1) 
  3.  
  4. // no need for .value anymore! 
  5. console.log(count) // 1 
  6.  
  7. function inc() { 
  8.   // assignments are reactive 
  9.   count++ 

另外,這是一項實驗性功能。實驗性功能可能會改變補丁版本之間的行為。建議將您的 vue 依賴項固定到確切的版本以避免損壞。

言歸正傳,我們來看下ref-macros.d.ts文件中的內(nèi)容。

  1. import type { 
  2.   Ref, 
  3.   UnwrapRef, 
  4.   ComputedRef, 
  5.   WritableComputedOptions, 
  6.   WritableComputedRef, 
  7.   ShallowUnwrapRef, 
  8. from '@vue/composition-api' 
  9.  
  10. declare const RefMarker: unique symbol 
  11.   type RefValue<T> = T & { [RefMarker]?: any } 
  12.  
  13. declare const ComputedRefMarker: unique symbol 
  14.   type ComputedRefValue<T> = T & { [ComputedRefMarker]?: any } 
  15.  
  16. declare const WritableComputedRefMarker: unique symbol 
  17.   type WritableComputedRefValue<T> = T & { [WritableComputedRefMarker]?: any } 
  18.  
  19.   type ToRawRefs<T extends object> = { 
  20.     [K in keyof T]: T[K] extends ComputedRefValue<infer V> 
  21.       ? ComputedRefValue<V> 
  22.       : T[K] extends WritableComputedRefValue<infer V> 
  23.         ? WritableComputedRef<V> 
  24.         : T[K] extends RefValue<infer V> 
  25.           ? Ref<V> 
  26.           : T[K] extends object 
  27.             ? T[K] extends 
  28.             | Function 
  29.             | Map<anyany
  30.             | Set<any
  31.             | WeakMap<anyany
  32.             | WeakSet<any
  33.               ? T[K] 
  34.               : ToRawRefs<T[K]> 
  35.             : T[K]; 
  36.   } 
  37.  
  38. /** 
  39.    * Vue ref transform macro for binding refs as reactive variables. 
  40.    */ 
  41. declare function _$<T>(arg: ComputedRef<T>): ComputedRefValue<T> 
  42. declare function _$<T>( 
  43.   arg: WritableComputedRef<T> 
  44. ): WritableComputedRefValue<T> 
  45. declare function _$<T>(arg: Ref<T>): RefValue<T> 
  46. declare function _$<T extends object>(arg?: T): ShallowUnwrapRef<T> 
  47.  
  48. /** 
  49.    * Vue ref transform macro for accessing underlying refs of reactive varaibles. 
  50.    */ 
  51. declare function _$$<T>(value: T): ComputedRef<T> 
  52. declare function _$$<T>( 
  53.   value: WritableComputedRefValue<T> 
  54. ): WritableComputedRef<T> 
  55. declare function _$$<T>(value: RefValue<T>): Ref<T> 
  56. declare function _$$<T extends object>(arg: T): ToRawRefs<T> 
  57.  
  58. declare function _$ref<T>(arg?: T | Ref<T>): RefValue<UnwrapRef<T>> 
  59.  
  60. declare function _$shallowRef<T>(arg?: T): RefValue<T> 
  61.  
  62. declare function _$computed<T>( 
  63.   getter: () => T, 
  64.   // debuggerOptions?: DebuggerOptions 
  65. ): ComputedRefValue<T> 
  66. declare function _$computed<T>( 
  67.   options: WritableComputedOptions<T>, 
  68.   // debuggerOptions?: DebuggerOptions 
  69. ): WritableComputedRefValue<T> 
  70.  
  71. declare global { 
  72.   const $: typeof _$ 
  73.   const $$: typeof _$$ 
  74.   const $ref: typeof _$ref 
  75.   const $shallowRef: typeof _$shallowRef 
  76.   const $computed: typeof _$computed 

tsconfig.json

tsconfig.json文件中指定了用來編譯這個項目的根文件和編譯選項。

我們這里需要注意如果您的 IDE 缺少全局類型。

  1.   "compilerOptions": { 
  2.     "types": [ 
  3.       "unplugin-vue2-script-setup/types" 
  4.     ] 
  5.   } 

Volar 優(yōu)先支持 Vue 3。Vue 3 和 Vue 2 模板有些不同。您需要設(shè)置 ExperimentCompatMode 選項以支持 Vue 2 模板。

  1.   "compilerOptions": { 
  2.     ... 
  3.   }, 
  4.   "vueCompilerOptions": { 
  5.     "experimentalCompatMode": 2 
  6.   }, 

最后,文件內(nèi)容如下:

  1.   "compilerOptions": { 
  2.     "target""es2017"
  3.     "module""esnext"
  4.     "moduleResolution""node"
  5.     "esModuleInterop"true
  6.     "strict"true
  7.     "strictNullChecks"true
  8.     "resolveJsonModule"true
  9.     "types": [ 
  10.       "unplugin-vue2-script-setup/types" 
  11.     ] 
  12.   }, 
  13.   "vueCompilerOptions": { 
  14.     "experimentalCompatMode": 2 
  15.   } 

vite.config.ts

這個文件是Vite的配置文件。當(dāng)以命令行方式運行 vite 時,Vite 會自動解析項目根目錄下名為 vite.config.js(或vite.config.ts) 的文件。

這里需要注意 refTransform 現(xiàn)在是插件根級選項,需要手動定義為true。(為什么配置refTransform,可以看上面ref-macros.d.ts文件中對refs處理,不使用.value的介紹)。

另外,如果想支持<script setup>語法,必須在這里以插件的形式配置。

  1. import { defineConfig } from 'vite' 
  2. import { createVuePlugin as Vue2 } from 'vite-plugin-vue2' 
  3. import ScriptSetup from 'unplugin-vue2-script-setup/vite' 
  4.  
  5. export default defineConfig({ 
  6.   plugins: [ 
  7.     Vue2(), 
  8.     ScriptSetup({ 
  9.       refTransform: true
  10.     }), 
  11.   ], 
  12. }) 

介紹完這些文件,剩下的就是src文件夾中的文件了,因為文件過多,我們把它單獨放在Src文件夾欄目中。

Src文件夾

assets文件中只有l(wèi)ogo.png一個圖片,你可以把靜態(tài)文件放在當(dāng)中,這里不多過介紹。

main.ts

這是Vue2的入口文件,我們可以看到這里VueCompositionAPI被當(dāng)做插件引入。另外,我們引入的App.vue以及其他*.vue為后綴的文件,需要有專門的類型定義文件進(jìn)行聲明,在下面的shims-vue.d.ts文件中我們會講到。

  1. import Vue from 'vue' 
  2. import VueCompositionAPI from '@vue/composition-api' 
  3. import App from './App.vue' 
  4.  
  5. Vue.use(VueCompositionAPI) 
  6.  
  7. const app = new Vue({ render: h => h(App) }) 
  8. app.$mount('#app'

shims-vue.d.ts

  1. declare module '*.vue' { 
  2.   import Vue from 'vue' 
  3.   export default Vue 

App.vue

這個文件是頁面入口文件。我們來看下它是如何寫的,這是Vue2項目,但是寫法與Vue3項目無異,只不過在Vue2項目中需要'@vue/composition-api'使用Composition-api,而Vue3項目直接引入vue。

另外,這里看到我們直接使用<script setup>語法,替換了之前setup()方法,使代碼更簡潔。還有我們可以直接引入組件,直接在模板中使用。

更多關(guān)于<script setup>語法的內(nèi)容可以看看https://v3.cn.vuejs.org/api/sfc-script-setup.html,了解更多使用方法。

  1. <template> 
  2.   <div id="app"
  3.     <img alt="Vue logo" src="./assets/logo.png"
  4.     <hello-world name="Vue 2 + TypeScript + Vite" @update="onUpdate" /> 
  5.     <async-component /> 
  6.   </div> 
  7. </template> 
  8.  
  9. <script setup lang="ts"
  10. import { defineAsyncComponent } from '@vue/composition-api' 
  11.  
  12. import HelloWorld from './components/HelloWorld.vue' 
  13.  
  14. const AsyncComponent = defineAsyncComponent(() => import('./components/Async.vue')) 
  15.  
  16. function onUpdate(e: any) { 
  17.   console.log(e) 
  18. </script> 
  19. <script lang="ts"
  20. export default { 
  21.   name'App'
  22. </script> 
  23. <style> 
  24. #app { 
  25.   font-family: Avenir, Helvetica, Arial, sans-serif; 
  26.   -webkit-font-smoothing: antialiased; 
  27.   -moz-osx-font-smoothing: grayscale; 
  28.   text-align: center; 
  29.   color: #2c3e50; 
  30.   margin-top: 60px; 
  31. </style> 

HelloWorld.vue

然后,我們再看下這個文件中什么內(nèi)容。這里需要注意的是$ref()、$computed()方法,這就是之前提到的refTransform語法,不得不說,這比以前使用.value處理方便多了。

  1. <template> 
  2.   <div> 
  3.     <h1>{{ msg }}, {{ name }}</h1> 
  4.     <button @click="inc"
  5.       Inc 
  6.     </button> 
  7.     <div>{{ count }} x 2 = {{ doubled }}</div> 
  8.     <button @click="dec()" v-html="decText" /> 
  9.     <component :is="count > 2 ? Foo : Bar" /> 
  10.   </div> 
  11. </template> 
  12.  
  13. <script setup lang="ts"
  14. import { watch } from '@vue/composition-api' 
  15. import Foo from './Foo.vue' 
  16. import Bar from './Bar.vue' 
  17.  
  18. const props = withDefaults(defineProps<{ msg: string; name: string | number }>(), { msg: 'Hello' }) 
  19. const emit = defineEmits(['update']) 
  20.  
  21. let count = $ref(1) 
  22. // eslint-disable-next-line prefer-const 
  23. let doubled = $computed(() => count * 2) 
  24.  
  25. function inc() { 
  26.   count += 1 
  27. function dec() { 
  28.   count -= 1 
  29.  
  30. const decText = '<b>Dec</b>' 
  31.  
  32. watch(()=>count, value => emit('update', value)) 
  33. </script> 
  34. <style scoped> 
  35. button{ 
  36.   margin: 20px 0; 
  37. </style> 

其他文件就不過多介紹了,就只是簡單的模板文件。

Foo.vue

  1. <template> 
  2.   <div>Foo</div> 
  3. </template> 

Bar.vue

  1. <template> 
  2.   <div>Bar</div> 
  3. </template> 

Async.vue

  1. <template> 
  2.   <div>Async Component</div> 
  3. </template> 

結(jié)語

最后,我們啟動下項目。

  1. yarn dev 

如上圖所示,啟動成功。

相信這樣可以在一定程度上提升你 Vue 2 的開發(fā)體驗,趕快來!

以下是本篇文章的源碼地址:

  1. https://github.com/maomincoding/viteVue2p 

如果覺得這篇文章對你有幫助,感謝點贊哦~

本文轉(zhuǎn)載自微信公眾號「前端歷劫之路」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系前端歷劫之路公眾號。

 

責(zé)任編輯:武曉燕 來源: 前端歷劫之路
相關(guān)推薦

2021-03-22 05:58:22

Vite2TypeScript4Vue3

2020-09-19 21:15:26

Composition

2022-05-17 08:39:05

VueViteTypeScript

2021-07-06 07:02:41

Vue 2 Vite 開發(fā)工具

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2021-07-26 10:00:55

script-setuAPI前端

2024-03-01 11:32:22

Vue3APIVue.js

2021-07-08 00:01:45

Vue2CompositionAPI

2024-10-18 10:49:03

Actions異步函數(shù)

2025-04-09 09:10:00

開發(fā)ViteVue

2022-07-13 10:07:31

vue3組件監(jiān)聽器

2021-12-15 08:23:42

Vue3 插件Vue應(yīng)用

2021-09-15 07:56:32

TypeScriptVue項目

2011-09-02 14:35:32

UbuntuAndroidlinux

2021-08-11 08:31:42

前端技術(shù)Vue3

2021-05-24 08:04:03

script setuVue Vue 3

2022-08-15 07:34:36

vite項目Vue3

2023-04-27 11:07:24

Setup語法糖Vue3

2022-07-28 08:26:18

Vue3Uni-appVite

2025-01-20 00:00:06

Vue開發(fā)工具庫
點贊
收藏

51CTO技術(shù)棧公眾號