Vue3 + TypeScript 開發實踐總結

前言

遲來的Vue3文章,其實早在今年3月份時就把Vue3過了一遍。<br/>在去年年底又把 TypeScript 從新學了一遍,爲了上 Vue3 的車,更好的開車。<br/>在上家公司4月份時,上級領導分配了一個內部的 黨務系統開發 ,這個系統前端是由我一我的來開發,功能和需求也不怎麼複雜的一個B 端 系統,直接上的 Vue3 + TypeScript + Element Plus 開發的,開發兩週到最後的上線,期間也遇到不少小坑,不少無處可查,慢慢琢磨最後仍是克服了。javascript

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 中編寫組件中的另外一種方法,內部簡化了好多操做。vue

因此你還能夠繼續使用 Vue2 的方式來 編寫 組件。java

3.2 何時使用Composition Api

  1. TypeScript` 的支持
  2. 編寫大型組件時,可使用 Composition Api 組合函數很好的管理狀態
  3. 跨組件重用代碼時

四,Composition Api 必備基礎

4.1 什麼是 setup

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

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

注意:

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

4.2 ref 建立響應式變量

Vue2 中,咱們定義一個響應式變量能夠直接在 data 中 定義而且在模板中使用該變量。 若是 使用的 composition api 的話,咱們得在 setup 中 使用 ref 來建立 響應式變量,而且得將它返回,才能在頁面中使用。npm

使用

    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` api

sd ide

下面代碼中有兩個 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}

最後

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

相關文章
相關標籤/搜索