vue3.0學習筆記

1.Vue3簡介

2.Vue3帶來了什么

1.性能的提升

  • 打包大小減少41%

  • 初次渲染快55%, 更新渲染快133%

  • 內(nèi)存減少54%

    ......

2.源碼的升級

  • 使用Proxy代替defineProperty實現(xiàn)響應式

  • 重寫虛擬DOM的實現(xiàn)和Tree-Shaking

    ......

3.擁抱TypeScript

  • Vue3可以更好的支持TypeScript

4.新的特性

  1. Composition API(組合API)

    • setup配置
    • ref與reactive
    • watch與watchEffect
    • provide與inject
    • ......
  2. 新的內(nèi)置組件

    • Fragment
    • Teleport
    • Suspense
  3. 其他改變

    • 新的生命周期鉤子
    • data 選項應始終被聲明為一個函數(shù)
    • 移除keyCode支持作為 v-on 的修飾符
    • ......

一、創(chuàng)建Vue3.0工程

1.使用 vue-cli 創(chuàng)建

官方文檔:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create

## 查看@vue/cli版本,確保@vue/cli版本在4.5.0以上
vue --version
## 安裝或者升級你的@vue/cli
npm install -g @vue/cli
## 創(chuàng)建
vue create vue_test
## 啟動
cd vue_test
npm run serve

2.使用 vite 創(chuàng)建

官方文檔:https://v3.cn.vuejs.org/guide/installation.html#vite

vite官網(wǎng):https://vitejs.cn

  • 什么是vite?—— 新一代前端構(gòu)建工具。
  • 優(yōu)勢如下:
    • 開發(fā)環(huán)境中,無需打包操作,可快速的冷啟動。
    • 輕量快速的熱重載(HMR)。
    • 真正的按需編譯,不再等待整個應用編譯完成。
## 創(chuàng)建工程
npm init vite-app <project-name>
## 進入工程目錄
cd <project-name>
## 安裝依賴
npm install
## 運行
npm run dev

二、常用 Composition API

官方文檔: https://v3.cn.vuejs.org/guide/composition-api-introduction.html

1.拉開序幕的setup

  1. 理解:Vue3.0中一個新的配置項,值為一個函數(shù)。
  2. setup是所有<strong style="color:#DD5145">Composition API(組合API)</strong><i style="color:gray;font-weight:bold">“ 表演的舞臺 ”</i>。
  3. 組件中所用到的:數(shù)據(jù)、方法等等,均要配置在setup中。
  4. setup函數(shù)的兩種返回值:
    1. 若返回一個對象,則對象中的屬性、方法, 在模板中均可以直接使用。(重點關(guān)注?。?/li>
    2. <span style="color:#aad">若返回一個渲染函數(shù):則可以自定義渲染內(nèi)容。(了解)</span>
  5. 注意點:
    1. 盡量不要與Vue2.x配置混用
      • Vue2.x配置(data、methos、computed...)中<strong style="color:#DD5145">可以訪問到</strong>setup中的屬性、方法。
      • 但在setup中<strong style="color:#DD5145">不能訪問到</strong>Vue2.x配置(data、methos、computed...)。
      • 如果有重名, setup優(yōu)先。
    2. setup不能是一個async函數(shù),因為返回值不再是return的對象, 而是promise, 模板看不到return對象中的屬性。(后期也可以返回一個Promise實例,但需要Suspense和異步組件的配合)

2.ref函數(shù)

  • 作用: 定義一個響應式的數(shù)據(jù)
  • 語法: const xxx = ref(initValue)
    • 創(chuàng)建一個包含響應式數(shù)據(jù)的<strong style="color:#DD5145">引用對象(reference對象,簡稱ref對象)</strong>。
    • JS中操作數(shù)據(jù): xxx.value
    • 模板中讀取數(shù)據(jù): 不需要.value,直接:<div>{{xxx}}</div>
  • 備注:
    • 接收的數(shù)據(jù)可以是:基本類型、也可以是對象類型。
    • 基本類型的數(shù)據(jù):響應式依然是靠Object.defineProperty()getset完成的。
    • 對象類型的數(shù)據(jù):內(nèi)部 <i style="color:gray;font-weight:bold">“ 求助 ”</i> 了Vue3.0中的一個新函數(shù)—— reactive函數(shù)。

3.reactive函數(shù)

  • 作用: 定義一個<strong style="color:#DD5145">對象類型</strong>的響應式數(shù)據(jù)(基本類型不要用它,要用ref函數(shù))
  • 語法:const 代理對象= reactive(源對象)接收一個對象(或數(shù)組),返回一個<strong style="color:#DD5145">代理對象(Proxy的實例對象,簡稱proxy對象)</strong>
  • reactive定義的響應式數(shù)據(jù)是“深層次的”。
  • 內(nèi)部基于 ES6 的 Proxy 實現(xiàn),通過代理對象操作源對象內(nèi)部數(shù)據(jù)進行操作。

4.Vue3.0中的響應式原理

vue2.x的響應式

  • 實現(xiàn)原理:

    • 對象類型:通過Object.defineProperty()對屬性的讀取、修改進行攔截(數(shù)據(jù)劫持)。

    • 數(shù)組類型:通過重寫更新數(shù)組的一系列方法來實現(xiàn)攔截。(對數(shù)組的變更方法進行了包裹)。

      Object.defineProperty(data, 'count', {
          get () {}, 
          set () {}
      })
      
  • 存在問題:

    • 新增屬性、刪除屬性, 界面不會更新。
    • 直接通過下標修改數(shù)組, 界面不會自動更新。

Vue3.0的響應式

5.reactive對比ref

  • 從定義數(shù)據(jù)角度對比:
    • ref用來定義:<strong style="color:#DD5145">基本類型數(shù)據(jù)</strong>。
    • reactive用來定義:<strong style="color:#DD5145">對象(或數(shù)組)類型數(shù)據(jù)</strong>。
    • 備注:ref也可以用來定義<strong style="color:#DD5145">對象(或數(shù)組)類型數(shù)據(jù)</strong>, 它內(nèi)部會自動通過reactive轉(zhuǎn)為<strong style="color:#DD5145">代理對象</strong>。
  • 從原理角度對比:
    • ref通過Object.defineProperty()getset來實現(xiàn)響應式(數(shù)據(jù)劫持)。
    • reactive通過使用<strong style="color:#DD5145">Proxy</strong>來實現(xiàn)響應式(數(shù)據(jù)劫持), 并通過<strong style="color:#DD5145">Reflect</strong>操作<strong style="color:orange">源對象</strong>內(nèi)部的數(shù)據(jù)。
  • 從使用角度對比:
    • ref定義的數(shù)據(jù):操作數(shù)據(jù)<strong style="color:#DD5145">需要</strong>.value,讀取數(shù)據(jù)時模板中直接讀取<strong style="color:#DD5145">不需要</strong>.value。
    • reactive定義的數(shù)據(jù):操作數(shù)據(jù)與讀取數(shù)據(jù):<strong style="color:#DD5145">均不需要</strong>.value。

6.setup的兩個注意點

  • setup執(zhí)行的時機

    • 在beforeCreate之前執(zhí)行一次,this是undefined。
  • setup的參數(shù)

    • props:值為對象,包含:組件外部傳遞過來,且組件內(nèi)部聲明接收了的屬性。
    • context:上下文對象
      • attrs: 值為對象,包含:組件外部傳遞過來,但沒有在props配置中聲明的屬性, 相當于 this.$attrs
      • slots: 收到的插槽內(nèi)容, 相當于 this.$slots。
      • emit: 分發(fā)自定義事件的函數(shù), 相當于 this.$emit

7.計算屬性與監(jiān)視

1.computed函數(shù)

  • 與Vue2.x中computed配置功能一致

  • 寫法

    import {computed} from 'vue'
    
    setup(){
        ...
      //計算屬性——簡寫
        let fullName = computed(()=>{
            return person.firstName + '-' + person.lastName
        })
        //計算屬性——完整
        let fullName = computed({
            get(){
                return person.firstName + '-' + person.lastName
            },
            set(value){
                const nameArr = value.split('-')
                person.firstName = nameArr[0]
                person.lastName = nameArr[1]
            }
        })
    }
    

2.watch函數(shù)

  • 與Vue2.x中watch配置功能一致

  • 兩個小“坑”:

    • 監(jiān)視reactive定義的響應式數(shù)據(jù)時:oldValue無法正確獲取、強制開啟了深度監(jiān)視(deep配置失效)。
    • 監(jiān)視reactive定義的響應式數(shù)據(jù)中某個屬性時:deep配置有效。
    //情況一:監(jiān)視ref定義的響應式數(shù)據(jù)
    watch(sum,(newValue,oldValue)=>{
      console.log('sum變化了',newValue,oldValue)
    },{immediate:true})
    
    //情況二:監(jiān)視多個ref定義的響應式數(shù)據(jù)
    watch([sum,msg],(newValue,oldValue)=>{
      console.log('sum或msg變化了',newValue,oldValue)
    }) 
    
    /* 情況三:監(jiān)視reactive定義的響應式數(shù)據(jù)
              若watch監(jiān)視的是reactive定義的響應式數(shù)據(jù),則無法正確獲得oldValue??!
              若watch監(jiān)視的是reactive定義的響應式數(shù)據(jù),則強制開啟了深度監(jiān)視 
    */
    watch(person,(newValue,oldValue)=>{
      console.log('person變化了',newValue,oldValue)
    },{immediate:true,deep:false}) //此處的deep配置不再奏效
    
    //情況四:監(jiān)視reactive定義的響應式數(shù)據(jù)中的某個屬性
    watch(()=>person.job,(newValue,oldValue)=>{
      console.log('person的job變化了',newValue,oldValue)
    },{immediate:true,deep:true}) 
    
    //情況五:監(jiān)視reactive定義的響應式數(shù)據(jù)中的某些屬性
    watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
      console.log('person的job變化了',newValue,oldValue)
    },{immediate:true,deep:true})
    
    //特殊情況
    watch(()=>person.job,(newValue,oldValue)=>{
        console.log('person的job變化了',newValue,oldValue)
    },{deep:true}) //此處由于監(jiān)視的是reactive素定義的對象中的某個屬性,所以deep配置有效
    

3.watchEffect函數(shù)

  • watch的套路是:既要指明監(jiān)視的屬性,也要指明監(jiān)視的回調(diào)。

  • watchEffect的套路是:不用指明監(jiān)視哪個屬性,監(jiān)視的回調(diào)中用到哪個屬性,那就監(jiān)視哪個屬性。

  • watchEffect有點像computed:

    • 但computed注重的計算出來的值(回調(diào)函數(shù)的返回值),所以必須要寫返回值。
    • 而watchEffect更注重的是過程(回調(diào)函數(shù)的函數(shù)體),所以不用寫返回值。
    //watchEffect所指定的回調(diào)中用到的數(shù)據(jù)只要發(fā)生變化,則直接重新執(zhí)行回調(diào)。
    watchEffect(()=>{
        const x1 = sum.value
        const x2 = person.age
        console.log('watchEffect配置的回調(diào)執(zhí)行了')
    })
    

8.生命周期

  • Vue3.0中可以繼續(xù)使用Vue2.x中的生命周期鉤子,但有有兩個被更名:
    • beforeDestroy改名為 beforeUnmount
    • destroyed改名為 unmounted
  • Vue3.0也提供了 Composition API 形式的生命周期鉤子,與Vue2.x中鉤子對應關(guān)系如下:
    • beforeCreate===>setup()
    • created=======>setup()
    • beforeMount ===>onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==>onBeforeUnmount
    • unmounted =====>onUnmounted

9.自定義hook函數(shù)

  • 什么是hook?—— 本質(zhì)是一個函數(shù),把setup函數(shù)中使用的Composition API進行了封裝。

  • 類似于vue2.x中的mixin。

  • 自定義hook的優(yōu)勢: 復用代碼, 讓setup中的邏輯更清楚易懂。

10.toRef

  • 作用:創(chuàng)建一個 ref 對象,其value值指向另一個對象中的某個屬性。
  • 語法:const name = toRef(person,'name')
  • 應用: 要將響應式對象中的某個屬性單獨提供給外部使用時。
  • 擴展:toRefstoRef功能一致,但可以批量創(chuàng)建多個 ref 對象,語法:toRefs(person)

三、其它 Composition API

1.shallowReactive 與 shallowRef

  • shallowReactive:只處理對象最外層屬性的響應式(淺響應式)。

  • shallowRef:只處理基本數(shù)據(jù)類型的響應式, 不進行對象的響應式處理。

  • 什么時候使用?

    • 如果有一個對象數(shù)據(jù),結(jié)構(gòu)比較深, 但變化時只是外層屬性變化 ===> shallowReactive。
    • 如果有一個對象數(shù)據(jù),后續(xù)功能不會修改該對象中的屬性,而是生新的對象來替換 ===> shallowRef。

2.readonly 與 shallowReadonly

  • readonly: 讓一個響應式數(shù)據(jù)變?yōu)橹蛔x的(深只讀)。
  • shallowReadonly:讓一個響應式數(shù)據(jù)變?yōu)橹蛔x的(淺只讀)。
  • 應用場景: 不希望數(shù)據(jù)(尤其是這個數(shù)據(jù)是來自與其他組件時)被修改時。

3.toRaw 與 markRaw

  • toRaw:
    • 作用:將一個由reactive生成的<strong style="color:orange">響應式對象</strong>轉(zhuǎn)為<strong style="color:orange">普通對象</strong>。
    • 使用場景:用于讀取響應式對象對應的普通對象,對這個普通對象的所有操作,不會引起頁面更新。
  • markRaw:
    • 作用:標記一個對象,使其永遠不會再成為響應式對象。
    • 應用場景:
      1. 有些值不應被設(shè)置為響應式的,例如復雜的第三方類庫等。
      2. 當渲染具有不可變數(shù)據(jù)源的大列表時,跳過響應式轉(zhuǎn)換可以提高性能。

4.customRef

  • 作用:創(chuàng)建一個自定義的 ref,并對其依賴項跟蹤和更新觸發(fā)進行顯式控制。

  • 實現(xiàn)防抖效果:

    <template>
      <input type="text" v-model="keyword">
      <h3>{{keyword}}</h3>
    </template>
    
    <script>
      import {ref,customRef} from 'vue'
      export default {
          name:'Demo',
          setup(){
              // let keyword = ref('hello') //使用Vue準備好的內(nèi)置ref
              //自定義一個myRef
              function myRef(value,delay){
                  let timer
                  //通過customRef去實現(xiàn)自定義
                  return customRef((track,trigger)=>{
                      return{
                          get(){
                              track() //告訴Vue這個value值是需要被“追蹤”的
                              return value
                          },
                          set(newValue){
                              clearTimeout(timer)
                              timer = setTimeout(()=>{
                                  value = newValue
                                  trigger() //告訴Vue去更新界面
                              },delay)
                          }
                      }
                  })
              }
              let keyword = myRef('hello',500) //使用程序員自定義的ref
              return {
                  keyword
              }
          }
      }
    </script>
    

5.provide 與 inject

<img src="https://v3.cn.vuejs.org/images/components_provide.png" style="width:300px" />

  • 作用:實現(xiàn)<strong style="color:#DD5145">祖與后代組件間</strong>通信

  • 套路:父組件有一個 provide 選項來提供數(shù)據(jù),后代組件有一個 inject 選項來開始使用這些數(shù)據(jù)

  • 具體寫法:

    1. 祖組件中:

      setup(){
          ......
          let car = reactive({name:'奔馳',price:'40萬'})
          provide('car',car)
          ......
      }
      
    2. 后代組件中:

      setup(props,context){
          ......
          const car = inject('car')
          return {car}
          ......
      }
      

6.響應式數(shù)據(jù)的判斷

  • isRef: 檢查一個值是否為一個 ref 對象
  • isReactive: 檢查一個對象是否是由 reactive 創(chuàng)建的響應式代理
  • isReadonly: 檢查一個對象是否是由 readonly 創(chuàng)建的只讀代理
  • isProxy: 檢查一個對象是否是由 reactive 或者 readonly 方法創(chuàng)建的代理

四、Composition API 的優(yōu)勢

1.Options API 存在的問題

使用傳統(tǒng)OptionsAPI中,新增或者修改一個需求,就需要分別在data,methods,computed里修改 。

[圖片上傳失敗...(image-51a807-1667977975561)]

[圖片上傳失敗...(image-dd6b32-1667977975562)]

2.Composition API 的優(yōu)勢

我們可以更加優(yōu)雅的組織我們的代碼,函數(shù)。讓相關(guān)功能的代碼更加有序的組織在一起。

[圖片上傳失敗...(image-3b6f95-1667977975562)]

[圖片上傳失敗...(image-52429-1667977975562)]

五、新的組件

1.Fragment

  • 在Vue2中: 組件必須有一個根標簽
  • 在Vue3中: 組件可以沒有根標簽, 內(nèi)部會將多個標簽包含在一個Fragment虛擬元素中
  • 好處: 減少標簽層級, 減小內(nèi)存占用

2.Teleport

  • 什么是Teleport?—— Teleport 是一種能夠?qū)⑽覀兊?lt;strong style="color:#DD5145">組件html結(jié)構(gòu)</strong>移動到指定位置的技術(shù)。

    <teleport to="移動位置">
      <div v-if="isShow" class="mask">
          <div class="dialog">
              <h3>我是一個彈窗</h3>
              <button @click="isShow = false">關(guān)閉彈窗</button>
          </div>
      </div>
    </teleport>
    

3.Suspense

  • 等待異步組件時渲染一些額外內(nèi)容,讓應用有更好的用戶體驗

  • 使用步驟:

    • 異步引入組件

      import {defineAsyncComponent} from 'vue'
      const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
      
    • 使用Suspense包裹組件,并配置好defaultfallback

      <template>
          <div class="app">
              <h3>我是App組件</h3>
              <Suspense>
                  <template v-slot:default>
                      <Child/>
                  </template>
                  <template v-slot:fallback>
                      <h3>加載中.....</h3>
                  </template>
              </Suspense>
          </div>
      </template>
      

六、其他

1.全局API的轉(zhuǎn)移

  • Vue 2.x 有許多全局 API 和配置。

    • 例如:注冊全局組件、注冊全局指令等。

      //注冊全局組件
      Vue.component('MyButton', {
        data: () => ({
          count: 0
        }),
        template: '<button @click="count++">Clicked {{ count }} times.</button>'
      })
      
      //注冊全局指令
      Vue.directive('focus', {
        inserted: el => el.focus()
      }
      
  • Vue3.0中對這些API做出了調(diào)整:

    • 將全局的API,即:Vue.xxx調(diào)整到應用實例(app)上

      2.x 全局 API(Vue 3.x 實例 API (app)
      Vue.config.xxxx app.config.xxxx
      Vue.config.productionTip <strong style="color:#DD5145">移除</strong>
      Vue.component app.component
      Vue.directive app.directive
      Vue.mixin app.mixin
      Vue.use app.use
      Vue.prototype app.config.globalProperties

2.其他改變

  • data選項應始終被聲明為一個函數(shù)。

  • 過度類名的更改:

    • Vue2.x寫法

      .v-enter,
      .v-leave-to {
        opacity: 0;
      }
      .v-leave,
      .v-enter-to {
        opacity: 1;
      }
      
    • Vue3.x寫法

      .v-enter-from,
      .v-leave-to {
        opacity: 0;
      }
      
      .v-leave-from,
      .v-enter-to {
        opacity: 1;
      }
      
  • <strong style="color:#DD5145">移除</strong>keyCode作為 v-on 的修飾符,同時也不再支持config.keyCodes

  • <strong style="color:#DD5145">移除</strong>v-on.native修飾符

    • 父組件中綁定事件

      <my-component
        v-on:close="handleComponentEvent"
        v-on:click="handleNativeClickEvent"
      />
      
    • 子組件中聲明自定義事件

      <script>
        export default {
          emits: ['close']
        }
      </script>
      
  • <strong style="color:#DD5145">移除</strong>過濾器(filter)

    過濾器雖然這看起來很方便,但它需要一個自定義語法,打破大括號內(nèi)表達式是 “只是 JavaScript” 的假設(shè),這不僅有學習成本,而且有實現(xiàn)成本!建議用方法調(diào)用或計算屬性去替換過濾器。

  • ......

//biji克隆地址
https://github.com/Panyue-genkiyo/vue3-learning.git
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容