Vue3 + TypeScript 開發實踐總結


 

微信截圖_20210708223623

前言

遲來的Vue3文章,其實早在今年3月份時就把Vue3過了一遍。
在去年年末又把 TypeScript 重新學了一遍,為了上 Vue3 的車,更好的開車。
在上家公司4月份時,上級領導分配了一個內部的 黨務系統開發 ,這個系統前端是由我一個人來開發,功能和需求也不怎么復雜的一個B 端 系統,直接上的 Vue3 + TypeScript + Element Plus 開發的,開發兩周到最后的上線,期間也遇到很多小坑,很多無處可查,慢慢琢磨最后還是克服了。

Vue3 + TypeScript Study

Vue 3

一, 環境配置

1.1 安裝最新 Vue 腳手架

npm install -g @vue/cli

yarn global add @vue/cli 

1.2 創建Vue3 項目

vue create projectName

1.3 現有Vue 2 項目 升級到 Vue3

vue add typescript

二, 進擊Vue3

2. 1 Vue 2 局限性

  1. 隨着組件與組件依賴之間不斷變大,組件很難讀取和維護

  2. 沒有完美的方法解決跨組件代碼重用

2.2 Vue 3 如何解決Vue 2 局限

  1. 組件難以維護管理

【在Vue3 中 編寫組合函數,使用 Compositon Api setUp 來解決】

  1. 沒有完美的方法解決跨組件代碼重用

三,Vue3 Composition Ap i

3.1 關於 Composition Api

在Vue3中,也可以不使用 Composition Api 來編寫組件,它只是在Vue3 中編寫組件中的另一種方法,內部簡化了好多操作。

所以你還可以繼續使用 Vue2 的方式來 編寫 組件。

3.2 什么時候使用Composition Api

  1. TypeScript` 的支持

  2. 編寫大型組件時,可以使用 Composition Api 組合函數很好的管理狀態

  3. 跨組件重用代碼時

四,Composition Api 必備基礎

4.1 什么是 setup

setup 是用來配置組件狀態的另一種實現。

在setup 中定義的狀態,方法要想在模板中使用,必須 return

注意:

  • setup 方法是在 components , props data Methods Computed Lifecycle methods 之前執行
  • 同時在 setup 中是不能訪問 this

4.2 ref 創建響應式變量

Vue2 中,我們定義一個響應式變量可以直接在 data 中 定義並且在模板中使用該變量。 如果 使用的 composition api 的話,我們得在 setup 中 使用 ref 來創建 響應式變量,並且得將它返回,才能在頁面中使用。

使用

    1. 引入 ref import { ref } from 'vue'
    1. 初始變量 const name = ref('指定默認值')
    1. 返回變量 return { name } 在return中還可以返回方法
    1. setup 中 訪問 定義的變量值,不能直接通過變量名來獲取, 必須通過 變量名.value 來獲取到該對象 、 值

這樣的好處

  • 狀態好管理,可以划分好幾個 setup 狀態管理,最后在一個 文件導入所有,並且使用。
<template>
    <div> <h1>{{title}}</h1> </div> </template> <script> import {ref,defineComponent} from 'vue' export default defineComponent({ setup () { // 定義響應式變量 const title = ref('前端自學社區') // 訪問該變量 console.log(title.value) // 返回變量 return {title} } }) </script> 

4.3 生命周期

Composition Api 生命周期鈎子 和 Vue 2 選項式 生命周期鈎子名稱一樣,只是在使用 組合式API時,前綴為 on, onMounted`

sd

下面代碼中有兩個 mounted 生命鈎子,你猜哪個會先執行?

setup 會先執行

    setup () {
        // 定義響應式變量 const title = ref('前端自學社區') console.log(title) // 返回變量 function getTitle(){ console.log(title.value) } // 頁面在加載 onMounted(getTitle) return {title} }, mounted() { console.log('測試 mounted 執行順序') }, 

4.4 watch

setup 中使用 watch響應式更改

  • 引入 watch, import { watch } from 'vue'

  • 直接使用watch,watch 接受 3 個參數

    1. 要監聽更新的 響應式引用或者 getter 函數
    2. 一個回調用來做更新后的操作
    3. 可選配置項
import {wathc} from 'vue' // 定義響應式變量 const num = ref(0) // 更新響應式變量 function changeNum(){ num.value++ } // wathc 監聽響應式變量 watch( num,(newValue, oldValue) => { console.log(`newValue為:${newValue},--------oldValue為:${oldValue}`) } ) 

4.5 computed

它也是 從 vue 導入,computed 函數返回一個作為 computed 的第一個參數傳遞的 getter 類回調的輸出的一個只讀響應式引用。為了訪問新創建的計算變量的 value,我們需要像使用 ref 一樣使用 .value property。

**當num值變化時,nums 的值會 *3 **

import {ref,computed} from 'vue'; const num = ref(0) //更新num function changeNum(){ num.value++ } //監聽num變化 const nums = computed(() =>{ return num.value * 3 }) 

五,setup

5.1 接受兩個參數

props: 父組件傳遞過來的屬性, setup` 函數中 props 是響應式的,它會隨着數據更新而更新,並且不能使用 ES6 解構,因為它會不能使 props 為響應式。

context : 它是一個普通的 對象,它暴露3個組件的· property

  1. Attribute
  2. 插槽
  3. 觸發事件

context 不是 響應式的,所以可以使用ES6 解構來簡便寫法。

   props:{
        obj:{ type:Object } }, setup (props,{attrs,slots,emit}) { console.log(attrs) console.log(slots) console.log(emit) console.log(props.obj) } 

5.2 組件加載 setup 時注意

在組件執行 setup 時, 組件實例沒有被創建,因此就無法訪問以下屬性

  • data
  • computed
  • methods

六,生命周期

setup 中使用 生命周期時,前綴必須加 on.

選項式 API Hook inside setup
beforeCreate  
created  
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

七, 跨組件之間傳值

Vue 2 中,我們可以使用 Provide/Inject 跨組件傳值,在 Vue 3 中也可以。

setup 中 使用,必須從 vue 中導入使用。

使用 Provide 時,一般設置為 響應式更新的,這樣的話,父組件變更,子組件,子孫組件也跟着更新。

怎么設置為響應式更新呢?

  1. 使用 ref / reactive 創建響應式變量
  2. 使用 provide('name', '要傳遞的響應式變量')
  3. 最后添加一個更新 響應式變量的事件,這樣響應式變量更新, provide 中的變量也跟着更新。

父組件

父組件
import { provide, defineComponent, ref, reactive } from "vue"; <template> <Son/> </template> <script> import { provide, defineComponent, ref, reactive } from "vue"; export default defineComponent({ setup() { const father = ref("我父組件"); const info = reactive({ id: 23, message: "前端自學社區", }); function changeProvide(){ info.message = '測試' } provide('father',father) provide('info',info) return {changeProvide}; } }) </script> 

子組件

<template>
    <div> <h1>{{info.message}}</h1> <h1>{{fatherData}}</h1> </div> </template> <script> import {provide, defineComponent,ref,reactive, inject} from 'vue' export default defineComponent({ setup () { const fatherData = inject('father') const info = inject('info') return {fatherData,info} } }) </script> 

八, 在Vue 中 使用 TypeScirpt 技巧

8.1 接口約束約束屬性

采用 TypeScirpt 的特性, 類型斷言 + 接口 完美的對 屬性進行了 約束

interface
分頁查詢 字段屬性類型驗證
export default interface queryType{ page: Number, size: Number, name: String, age: Number } 
組件中使用
import queryType from '../interface/Home' data() { return { query:{ page:0, size:10, name:'測試', age: 2 } as queryType } }, 

8.2 組件使用 來 defineComponent 定義

這樣 TypeScript 正確推斷 Vue 組件選項中的類型

import { defineComponent } from 'vue' export default defineComponent({ setup(){ return{ } } }) 

8.3 類型聲明 reactive

export default interface Product { name:String, price:Number, address:String } import Product from '@/interface/Product' import {reactive} from 'vue' const product = reactive({name:'xiaomi 11',price:5999,address:'北京'}) as Product return {fatherData,info,product} 

最后

文中如有錯誤,歡迎碼友在評論區指正,如果對你有所幫助,歡迎點贊和關注~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM