Vue3 + TypeScript 開發實踐總結

小阿鑫發表於2021-07-13

微信截圖_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}

最後

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

相關文章