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

使用Vue3的CompositionAPI來優(yōu)化代碼量

開發(fā) 前端
在我的開源項目中有一個組件是用來發(fā)送消息和展示消息的,這個組件的邏輯很復雜也是我整個項目的靈魂所在,單文件代碼有1100多行。我每次用webstorm編輯這個文件時,電腦cpu溫度都會飆升并伴隨著卡頓。

[[376028]]

本文轉載自微信公眾號「神奇的程序員k」,作者神奇的程序員k 。轉載本文請聯(lián)系神奇的程序員k公眾號。

前言

在我的開源項目中有一個組件是用來發(fā)送消息和展示消息的,這個組件的邏輯很復雜也是我整個項目的靈魂所在,單文件代碼有1100多行。我每次用webstorm編輯這個文件時,電腦cpu溫度都會飆升并伴隨著卡頓。

就在前幾天我終于忍不住了,意識到了Vue2的optionsAPI的缺陷,決定用Vue3的CompositionAPI來解決這個問題,本文就跟大家分享下我在優(yōu)化過程中踩到的坑以及我所采用的解決方案,歡迎各位感興趣的開發(fā)者閱讀本文。

問題分析

我們先來看看組件的整體代碼結構,如下圖所示:

image-20210114095802363

  • template部分占用267行
  • script部分占用889行
  • style部分為外部引用占用1行

罪魁禍首就是script部分,本文要優(yōu)化的就是這一部分的代碼,我們再來細看下script中的代碼結構:

  • props部分占用6行
  • data部分占用52行
  • created部分占用8行
  • mounted部分占用98行
  • methods部分占用672行
  • emits部分占用6行
  • computed部分占用8行
  • watch部分占用26行

現(xiàn)在罪魁禍首是methods部分,那么我們只需要把methods部分的代碼拆分出去,單文件代碼量就大大減少了。

優(yōu)化方案

經過上述分析后,我們已經知道了問題所在,接下來就跟大家分享下我一開始想到的方案以及最終所采用的方案。

直接拆分成文件

一開始我覺得既然methods方法占用的行數(shù)太多,那么我在src下創(chuàng)建一個methods文件夾,把每個組件中的methods的方法按照組件名進行劃分,創(chuàng)建對應的文件夾,在對應的組件文件夾內部,將methods中的方法拆分成獨立的ts文件,最后創(chuàng)建index.ts文件,將其進行統(tǒng)一導出,在組件中使用時按需導入index.ts中暴露出來的模塊,如下圖所示:

image-20210114103824562

  • 創(chuàng)建methods文件夾
  • 把每個組件中的methods的方法按照組件名進行劃分,創(chuàng)建對應的文件夾,即:message-display
  • 將methods中的方法拆分成獨立的ts文件,即:message-display文件夾下的ts文件
  • 創(chuàng)建index.ts文件,即:methods下的index.ts文件

index.ts代碼

如下所示,我們將拆分的模塊方法進行導入,然后統(tǒng)一export出去

  1. import compressPic from "@/methods/message-display/CompressPic"
  2. import pasteHandle from "@/methods/message-display/PasteHandle"
  3.  
  4. export { compressPic, pasteHandle }; 

在組件中使用

最后,我們在組件中按需導入即可,如下所示:

  1. import { compressPic, pasteHandle } from "@/methods/index"
  2.  
  3. export default defineComponent({ 
  4.     mounted() { 
  5.       compressPic(); 
  6.       pasteHandle(); 
  7.     } 
  8. }) 

運行結果

當我自信滿滿的開始跑項目時,發(fā)現(xiàn)瀏覽器的控制臺報錯了,提示我this未定義,突然間我意識到將代碼拆分成文件后,this是指向那個文件的,并沒有指向當前組件實例,當然可以將this作為參數(shù)傳進去,但我覺得這樣并不妥,用到一個方法就傳一個this進去,會產生很多冗余代碼,因此這個方案被我pass了。

使用mixins

前一個方案因為this的問題以失敗告終,在Vue2.x的時候官方提供了mixins來解決this問題,我們使用mixin來定義我們的函數(shù),最后使用mixins進行混入,這樣就可以在任意地方使用了。

由于mixins是全局混入的,一旦有重名的mixin原來的就會被覆蓋,所以這個方案也不合適,pass。

image-20210114111746208

使用CompositionAPI

上述兩個方案都不合適,那 么CompositionAPI就剛好彌補上述方案的短處,成功的實現(xiàn)了我們想要實現(xiàn)的需求。

我們先來看看什么是CompositionAPI,正如文檔所述,我們可以將原先optionsAPI中定義的函數(shù)以及這個函數(shù)需要用到的data變量,全部歸類到一起,放到setup函數(shù)里,功能開發(fā)完成后,將組件需要的函數(shù)和data在setup進行return。

setup函數(shù)在創(chuàng)建組件之前執(zhí)行,因此它是沒有this的,這個函數(shù)可以接收2個參數(shù): props和context,他們的類型定義如下:

  1. interface Data { 
  2.   [key: string]: unknown 
  3.  
  4. interface SetupContext { 
  5.   attrs: Data 
  6.   slots: Slots 
  7.   emit: (event: string, ...args: unknown[]) => void 
  8. function setup(props: Data, context: SetupContext): Data 

我的組件需要拿到父組件傳過來的props中的值,需要通過emit來向父組件傳遞數(shù)據,props和context這兩個參數(shù)正好解決了我這個問題。

setup又是個函數(shù),也就意味著我們可以將所有的函數(shù)拆分成獨立的ts文件,然后在組件中導入,在setup中將其return給組件即可,這樣就很完美的實現(xiàn)了一開始我們一開始所說的的拆分。

實現(xiàn)思路

接下來的內容會涉及到響應性API,如果對響應式API不了解的開發(fā)者請先移步官方文檔。

我們分析出方案后,接下來我們就來看看具體的實現(xiàn)路:

  • 在組件的導出對象中添加setup屬性,傳入props和context
  • 在src下創(chuàng)建module文件夾,將拆分出來的功能代碼按組件進行劃分
  • 將每一個組件中的函數(shù)進一步按功能進行細分,此處我分了四個文件夾出來
    • common-methods 公共方法,存放不需要依賴組件實例的方法
    • components-methods 組件方法,存放當前組件模版需要使用的方法
    • main-entrance 主入口,存放setup中使用的函數(shù)
    • split-method 拆分出來的方法,存放需要依賴組件實例的方法,setup中函數(shù)拆分出來的文件也放在此處
  • 在主入口文件夾中創(chuàng)建InitData.ts文件,該文件用于保存、共享當前組件需要用到的響應式data變量
  • 所有函數(shù)拆分完成后,我們在組件中將其導入,在setup中進行return即可

實現(xiàn)過程

接下來我們將上述思路進行實現(xiàn)。

添加setup選項

我們在vue組件的導出部分,在其對象內部添加setup選項,如下所示:

  1. <template> 
  2.   <!---其他內容省略--> 
  3. </template> 
  4. <script lang="ts"
  5. export default defineComponent({ 
  6.   name"message-display"
  7.   props: { 
  8.     listId: String, // 消息id 
  9.     messageStatus: Number, // 消息類型 
  10.     buddyId: String, // 好友id 
  11.     buddyName: String, // 好友昵稱 
  12.     serverTime: String // 服務器時間 
  13.   }, 
  14.   setup(props, context) { 
  15.     // 在此處即可寫響應性API提供的方法,注意⚠️此處不能用this 
  16.   } 
  17. </script> 

創(chuàng)建module模塊

我們在src下創(chuàng)建module文件夾,用于存放我們拆分出來的功能代碼文件。

如下所示,為我創(chuàng)建好的目錄,我的劃分依據是將相同類別的文件放到一起,每個文件夾的所代表的含義已在實現(xiàn)思路進行說明,此處不作過多解釋。

創(chuàng)建InitData.ts文件

我們將組件中用到的響應式數(shù)據,統(tǒng)一在這里進行定義,然后在setup中進行return,該文件的部分代碼定義如下,完整代碼請移步:InitData.ts

  1. import { 
  2.   reactive, 
  3.   Ref, 
  4.   ref, 
  5.   getCurrentInstance, 
  6.   ComponentInternalInstance 
  7. from "vue"
  8. import { 
  9.   emojiObj, 
  10.   messageDisplayDataType, 
  11.   msgListType, 
  12.   toolbarObj 
  13. from "@/type/ComponentDataType"
  14. import { Store, useStore } from "vuex"
  15.  
  16. // DOM操作,必須return否則不會生效 
  17. const messagesContainer = ref<HTMLDivElement | null>(null); 
  18. const msgInputContainer = ref<HTMLDivElement | null>(null); 
  19. const selectImg = ref<HTMLImageElement | null>(null); 
  20. // 響應式Data變量 
  21. const messageContent = ref<string>(""); 
  22. const emoticonShowStatus = ref<string>("none"); 
  23. const senderMessageList = reactive([]); 
  24. const isBottomOut = ref<boolean>(true); 
  25. let listId = ref<string>(""); 
  26. let messageStatus = ref<number>(0); 
  27. let buddyId = ref<string>(""); 
  28. let buddyName = ref<string>(""); 
  29. let serverTime = ref<string>(""); 
  30. let emit: (event: string, ...args: any[]) => void = () => { 
  31.   return 0; 
  32. }; 
  33. // store與當前實例 
  34. let $store = useStore(); 
  35. let currentInstance = getCurrentInstance(); 
  36.  
  37. export default function initData(): messageDisplayDataType { 
  38.   // 定義set方法,將props中的數(shù)據寫入當前實例 
  39.   const setData = ( 
  40.     listIdParam: Ref<string>, 
  41.     messageStatusParam: Ref<number>, 
  42.     buddyIdParam: Ref<string>, 
  43.     buddyNameParam: Ref<string>, 
  44.     serverTimeParam: Ref<string>, 
  45.     emitParam: (event: string, ...args: any[]) => void 
  46.   ) => { 
  47.     listId = listIdParam; 
  48.     messageStatus = messageStatusParam; 
  49.     buddyId = buddyIdParam; 
  50.     buddyName = buddyNameParam; 
  51.     serverTime = serverTimeParam; 
  52.     emit = emitParam; 
  53.   }; 
  54.   const setProperty = ( 
  55.     storeParam: Store<any>, 
  56.     instanceParam: ComponentInternalInstance | null 
  57.   ) => { 
  58.     $store = storeParam; 
  59.     currentInstance = instanceParam; 
  60.   }; 
  61.    
  62.   // 返回組件需要的Data 
  63.   return { 
  64.     messagesContainer, 
  65.     msgInputContainer, 
  66.     selectImg, 
  67.     $store, 
  68.     emoticonShowStatus, 
  69.     currentInstance, 
  70.     // .... 其他部分省略.... 
  71.     emit 
  72.   } 

??細心的開發(fā)者可能已經發(fā)現(xiàn),我把響應式變量定義在導出的函數(shù)外面了,之所以這么做是因為setup的一些特殊原因,在下面的踩坑章節(jié)我將會詳解我為什么要這樣做。

在組件中使用

定義完相應死變量后,我們就可以在組件中導入使用了,部分代碼如下所示,完整代碼請移步:message-display.vue

  1. import initData from "@/module/message-display/main-entrance/InitData"
  2.  
  3. export default defineComponent({ 
  4.    setup(props, context) { 
  5.     // 初始化組件需要的data數(shù)據 
  6.     const { 
  7.       createDisSrc, 
  8.       resourceObj, 
  9.       messageContent, 
  10.       emoticonShowStatus, 
  11.       emojiList, 
  12.       toolbarList, 
  13.       senderMessageList, 
  14.       isBottomOut, 
  15.       audioCtx, 
  16.       arrFrequency, 
  17.       pageStart, 
  18.       pageEnd, 
  19.       pageNo, 
  20.       pageSize, 
  21.       sessionMessageData, 
  22.       msgListPanelHeight, 
  23.       isLoading, 
  24.       isLastPage, 
  25.       msgTotals, 
  26.       isFirstLoading, 
  27.       messagesContainer, 
  28.       msgInputContainer, 
  29.       selectImg 
  30.     } = initData(); 
  31.       
  32.     // 返回組件需要用到的方法 
  33.     return { 
  34.       createDisSrc, 
  35.       resourceObj, 
  36.       messageContent, 
  37.       emoticonShowStatus, 
  38.       emojiList, 
  39.       toolbarList, 
  40.       senderMessageList, 
  41.       isBottomOut, 
  42.       audioCtx, 
  43.       arrFrequency, 
  44.       pageStart, 
  45.       pageEnd, 
  46.       pageNo, 
  47.       pageSize, 
  48.       sessionMessageData, 
  49.       msgListPanelHeight, 
  50.       isLoading, 
  51.       isLastPage, 
  52.       msgTotals, 
  53.       isFirstLoading, 
  54.       messagesContainer, 
  55.       msgInputContainer, 
  56.       selectImg 
  57.     }; 
  58.    } 
  59. }) 

我們定義后響應式變量后,就可以在拆分出來的文件中導入initData函數(shù),訪問里面存儲的變量了。

在文件中訪問initData

我將頁面內所有的事件監(jiān)聽也拆分成了文件,放在了EventMonitoring.ts中,在事件監(jiān)聽的處理函數(shù)是需要訪問initData里存儲的變量的,接下來我們就來看下如何訪問,部分代碼如下所示,完整代碼請移步EventMonitoring.ts)

  1. import { 
  2.   computed, 
  3.   Ref, 
  4.   ComputedRef, 
  5.   watch, 
  6.   getCurrentInstance, 
  7.   toRefs 
  8. from "vue"
  9. import { useStore } from "vuex"
  10. import initData from "@/module/message-display/main-entrance/InitData"
  11. import { SetupContext } from "@vue/runtime-core"
  12. import _ from "lodash"
  13.  
  14.  
  15. export default function eventMonitoring( 
  16.   props: messageDisplayPropsType, 
  17.   context: SetupContext<any
  18. ): { 
  19.   userID: ComputedRef<string>; 
  20.   onlineUsers: ComputedRef<number>; 
  21. } | void { 
  22.   const $store = useStore(); 
  23.   const currentInstance = getCurrentInstance(); 
  24.   // 獲取傳遞的參數(shù) 
  25.   const data = initData(); 
  26.   // 將props改為響應式 
  27.   const prop = toRefs(props); 
  28.   // 獲取data中的數(shù)據 
  29.   const senderMessageList = data.senderMessageList; 
  30.   const sessionMessageData = data.sessionMessageData; 
  31.   const pageStart = data.pageStart; 
  32.   const pageEnd = data.pageEnd; 
  33.   const pageNo = data.pageNo; 
  34.   const isLastPage = data.isLastPage; 
  35.   const msgTotals = data.msgTotals; 
  36.   const msgListPanelHeight = data.msgListPanelHeight; 
  37.   const isLoading = data.isLoading; 
  38.   const isFirstLoading = data.isFirstLoading; 
  39.   const listId = data.listId; 
  40.   const messageStatus = data.messageStatus; 
  41.   const buddyId = data.buddyId; 
  42.   const buddyName = data.buddyName; 
  43.   const serverTime = data.serverTime; 
  44.   const messagesContainer = data.messagesContainer as Ref<HTMLDivElement>; 
  45.    
  46.   // 監(jiān)聽listID改變 
  47.   watch(prop.listId, (newMsgId: string) => { 
  48.     listId.value = newMsgId; 
  49.     messageStatus.value = prop.messageStatus.value; 
  50.     buddyId.value = prop.buddyId.value; 
  51.     buddyName.value = prop.buddyName.value; 
  52.     serverTime.value = prop.serverTime.value; 
  53.     // 消息id發(fā)生改變,清空消息列表數(shù)據 
  54.     senderMessageList.length = 0; 
  55.     // 初始化分頁數(shù)據 
  56.     sessionMessageData.length = 0; 
  57.     pageStart.value = 0; 
  58.     pageEnd.value = 0; 
  59.     pageNo.value = 1; 
  60.     isLastPage.value = false
  61.     msgTotals.value = 0; 
  62.     msgListPanelHeight.value = 0; 
  63.     isLoading.value = false
  64.     isFirstLoading.value = true
  65.   }); 

正如代碼中那樣,在文件中使用時,拿出initData中對應的變量,需要修改其值時,只需要修改他的value即可。

至此,有關compositionAPI的基本使用就跟大家講解完了,下面將跟大家分享下我在實現(xiàn)過程中所踩的坑,以及我的解決方案。

踩坑分享

今天是周四,我周一開始決定使用CompositionAPI來重構我這個組件的,一直搞到昨天晚上才重構完成,前前后后踩了很多坑,正所謂踩坑越多你越強,這句話還是很有道理的??。

接下來就跟大家分享下我踩到的一些坑以及我的解決方案。

dom操作

我的組件需要對dom進行操作,在optionsAPI中可以使用this.$refs.xxx來訪問組件dom,在setup中是沒有this的,翻了下官方文檔后,發(fā)現(xiàn)需要通過ref來定義,如下所示:

  1. <template> 
  2. <div ref="msgInputContainer"></div> 
  3. <ul v-for="(item, i) in list" :ref="el => { ulContainer[i] = el }"></ul> 
  4. </template> 
  5.  
  6. <script lang="ts"
  7.   import { ref, reactive, onBeforeUpdate } from "vue"
  8.   setup(){ 
  9.     export default defineComponent({ 
  10.     // DOM操作,必須return否則不會生效 
  11.     // 獲取單一dom 
  12.     const messagesContainer = ref<HTMLDivElement | null>(null); 
  13.     // 獲取列表dom 
  14.     const ulContainer = ref<HTMLUListElement>([]); 
  15.     const list = reactive([1, 2, 3]); 
  16.     // 列表dom在組件更新前必須初始化 
  17.     onBeforeUpdate(() => { 
  18.        ulContainer.value = []; 
  19.     }); 
  20.     return { 
  21.       messagesContainer, 
  22.       list, 
  23.       ulContainer 
  24.     } 
  25.   }) 
  26.   } 
  27. </script> 

訪問vuex

在setup中訪問vuex需要通過useStore()來訪問,代碼如下所示:

  1. import { useStore } from "vuex"
  2.  
  3. const $store = useStore(); 
  4. console.log($store.state.token); 

訪問當前實例

在組件中需要訪問掛載在globalProperties上的東西,在setup中就需要通過getCurrentInstance()來訪問了,代碼如下所示:

  1. import { getCurrentInstance } from "vue"
  2.  
  3. const currentInstance = getCurrentInstance(); 
  4. currentInstance?.appContext.config.globalProperties.$socket.sendObj({ 
  5.   code: 200, 
  6.   token: $store.state.token, 
  7.   userID: $store.state.userID, 
  8.   msg: $store.state.userID + "上線" 
  9. }); 

無法訪問$options

我重構的websocket插件是將監(jiān)聽消息接收方法放在options上的,需要通過this.$options.xxx來訪問,文檔翻了一圈沒找到有關在setup中使用的內容,那看來是不能訪問了,那么我只能選擇妥協(xié),把插件掛載在options上的方法放到globalProperties上,這樣問題就解決了。

內置方法只能在setup中訪問

如上所述,我們使用到了getCurrentInstance和useStore,這兩個內置方法還有initData中定義的那些響應式數(shù)據,只有在setup中使用時才能拿到數(shù)據,否則就是null。

我的文件是拆分出去的,有些函數(shù)是運行在某個拆分出來的文件中的,不可能都在setup中執(zhí)行一遍的,響應式變量也不可能全當作參數(shù)進行傳遞的,為了解決這個問題,我有試過使用provide注入然后通過inject訪問,結果運行后發(fā)現(xiàn)不好使,控制臺報黃色警告說provide和inject只能運行在setup中,我直接裂開,當時發(fā)了一條沸點求助了下,到了晚上也沒得到解決方案??。

經過一番求助后,我的好友@前端印象給我提供了一個思路,成功的解決了這個問題,也就是我上面initData的做法,將響應式變量定義在導出函數(shù)的外面,這樣我們在拆分出來的文件中導入initData方法時,里面的變量都是指向同一個地址,可以直接訪問存儲在里面的變量且不會將其進行初始化。

至于getCurrentInstance和useStore訪問出現(xiàn)null的情景,還有props、emit的使用問題,我們可以在initData的導出函數(shù)內部定義set方法,在setup里的方法中獲取到實例后,通過set方法將其設置進我們定義的變量中。

至此,問題就完美解決了,最后跟大家看下優(yōu)化后的組件代碼,393行??

圖片

image-20210114201837539

項目地址

項目地址:chat-system-github

在線體驗地址:chat-system

 

責任編輯:武曉燕 來源: 神奇的程序員k
相關推薦

2020-11-12 08:32:14

Vue3模板優(yōu)化

2021-12-01 08:11:44

Vue3 插件Vue應用

2024-11-06 10:16:22

2021-12-29 07:51:21

Vue3 插件Vue應用

2021-11-30 08:19:43

Vue3 插件Vue應用

2023-11-28 09:03:59

Vue.jsJavaScript

2022-11-01 11:55:27

ReactVue3

2021-12-02 05:50:35

Vue3 插件Vue應用

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2020-09-19 21:15:26

Composition

2022-09-06 12:20:30

Vue3CVCRUD

2022-07-15 08:45:07

slotVue3

2021-06-26 06:29:14

Vue 2Vue 3開發(fā)

2021-11-17 08:24:47

Vue3 插件Vue應用

2022-07-08 08:52:25

Vue3組合動態(tài)返回

2021-05-20 07:26:21

工具Vuex Vue.js

2021-12-08 09:09:33

Vue 3 Computed Vue2

2024-03-01 11:32:22

Vue3APIVue.js

2024-10-14 09:34:39

vue3通信emit

2022-06-21 12:09:18

Vue差異
點贊
收藏

51CTO技術棧公眾號