關(guān)于Vue代碼可讀性的幾點建議
前言:
近來入坑了一個Vue項目,感覺掉進了祖?zhèn)魇荷街?,可讀性極差,更別說可維護性了。故借此專欄提幾點關(guān)于Vue代碼可讀性的建議,覺得有用的點個贊,覺得建議不合理的發(fā)表評論批評一下,有更好的建議歡迎發(fā)表評論補充一下。
一、善用組件讓代碼更有條理性
千萬不要把一個頁面的實現(xiàn)代碼都梭哈在一個.vue文件中,除非這個頁面非常簡單,不然這個.vue
文件中的代碼會又長又臭。
Vue
提供組件的目的不僅僅是為了復(fù)用,也可以用來分割代碼,甚至善用組件可以優(yōu)化頁面的渲染更新速度。 這是因為Vue頁面渲染更新時不會去更新頁面中的組件,除非組件的props
或者slot
所引用的數(shù)據(jù)發(fā)生變化。
可以按以下步驟來將一個Vue頁面分割成一個個組件讓代碼更有條理性
1、 提取UI組件
如何定義UI組件呢?個人建議按有無處理服務(wù)端數(shù)據(jù)來區(qū)分UI組件和業(yè)務(wù)組件。例如加載彈窗、二次確認(rèn)彈窗、消息提示框等等屬于UI交互組件。
將UI組件提取出來后,可以把UI交互的代碼和業(yè)務(wù)交互的代碼剝離開來。切記不能UI組件中寫業(yè)務(wù)代碼,這樣UI組件將無法復(fù)用。
舉一個反例,在二次確認(rèn)彈窗中添加二次確認(rèn)后要處理的業(yè)務(wù)代碼,導(dǎo)致UI組件將無法復(fù)用。我們可以模仿ElementUI中二次確認(rèn)彈窗的調(diào)用來實現(xiàn)一個二次確認(rèn)彈窗組件。
this.$confirm(message, title, options) .then(res =>{}) .catch(err =>{})
這樣業(yè)務(wù)代碼可以寫在then的回調(diào)函數(shù)中,組件的核心實現(xiàn)代碼如下所示:
//confirm.vue <template> <div v-show="show"> //... <div @click="ok"></div> <div @click="cancel"></div> </div> </template> <script> export default { data() { return { show: false, } }, methods: { ok() { this.show = false; this.resolve(); }, cancel() { this.show = false; this.resolve(); }, } } </script>
//index.js import Vue from 'vue'; import options from './confirm.vue'; const Confirm = Vue.extend(options); let confirm = undefined; const ConfirmInit = (options = {}) => { return new Promise((resolve, reject) => { options.resolve = resolve; options.reject = reject; confirm = new Confirm({ el: document.createElement('div'), data: options }) document.body.appendChild(confirm.$el); Vue.nextTick(() => { if (confirm) confirm.show = true; }) return confirm; }) } Vue.prototype.$confirm = ConfirmInit;
//main.js import 'components/confirm/index.js';//全局注冊二次確認(rèn)彈窗confirm組件
2、按模塊提取業(yè)務(wù)組件
一個頁面可以分為多個區(qū)域,比如頭部、底部、側(cè)邊欄、商品列表、成員列表等等,每個區(qū)域可以當(dāng)作一個模塊來提取業(yè)務(wù)組件。
3、按功能提取功能組件
按模塊提取完業(yè)務(wù)組件,此時業(yè)務(wù)組件有可能還是很龐大的,故要按功能在進一步地提取功能組件。
功能有大有小,提取要注意把握幾個原則:
過于簡單的功能不提?。?/strong>
例如一個收藏的功能,只要請求一個接口就完成,類似這樣的功能不要提取。要有一定復(fù)雜度的邏輯操作的功能才提取。
功能要單一:
一個功能組件只處理一項業(yè)務(wù)。
例如一個文件閱讀器組件,有一個需求,要求打開文件后自動收藏該文件,那么收藏邏輯代碼要寫在哪里呢?
或許你想都沒想就在組件中監(jiān)聽文件成功打開的方法中寫下收藏邏輯代碼,過一段時間后,需求改為要先添加到閱讀記錄中再點擊收藏按鈕收藏,去組件中修改代碼時發(fā)現(xiàn)另一個頁面也引用了這個組件,故在組件中要額外加個參數(shù)做業(yè)務(wù)場景區(qū)分,隨著需求的變化導(dǎo)致業(yè)務(wù)場景的疊加,組件的代碼中會添加各種判斷邏輯,久而久之變得又長又臭,顯然這種做法是不可去。
正確的做法是在組件標(biāo)簽上自定義一個事件on-fileOpen-success
,用handleFileOpenSuccess
函數(shù)來監(jiān)聽這個事件。
<fileReader @on-fileOpen-success="handleFileOpenSuccess" > </fileReader>
在組件中監(jiān)聽文件成功打開的方法中執(zhí)行this.$emit('on-fileOpen-success',data)
觸發(fā)這個事件,其中data
可以把文件信息傳遞出去,在handleFileOpenSuccess
函數(shù)去處理收藏或者添加歷史記錄再收藏等業(yè)務(wù)交互。這種做法使文件閱讀器組件具有單一性。
功能組件盡量少包含UI部分,UI部分用slot插槽傳入,這樣使組件更純粹,更具有復(fù)用性。
例如上傳組件的上傳圖標(biāo),不可能隨著UI設(shè)計稿的變動就往里面添加一個上傳圖標(biāo),此時可以利用slot插槽把上傳圖標(biāo)傳入。
//upload.vue <template> <div> <slot name="icon"></slot> </div> </template> //index.vue <template> <div> <upload> <template #icon> //上傳圖標(biāo) </template> </upload> </div> </template>
二、利用v-bind使組件的屬性更具有可讀性
如果想要將一個對象的所有屬性都作為prop
傳入組件componentA
,可以使用不帶參數(shù)的v-bind
。例如,對于一個給定的對象params
:
params: { id: 1, name: 'vue' }
優(yōu)化前:
<componentA :id="params.id" :name="params.name"></componentA>
優(yōu)化后:
<componentA v-bind="params"></componentA>
三、利用attrs與attrs與listeners來封裝第三方組件
1、$attrs
在封裝第三方組件中,經(jīng)常會遇到一個問題,如何通過封裝的組件去使用第三方組件自身的屬性和事件。
比如封裝一個elementUi
組件中的Input
輸入框組件myInput
,當(dāng)輸入錯誤的內(nèi)容在輸入框下面顯示錯誤的提示。
myInput
組件代碼如下所示:
<template> <div> <el-input v-model="input"></el-input> <div>{{errorTip}}</div> </div> </template> <script> export default { props: { value: { type: String, default: '', }, errorTip: { type: String, default: '', } }, data() { return { } }, computed: { input: { get() { return this.value }, set(val) { this.$emit('input', val) } } } } </script>
這樣調(diào)用myInput
組件,其中errorTip
為輸入框輸入錯誤的提示。
<myInput v-model="input" :errorTip="errorTip"></myInput>
如果要在myInput
組件上添加一個disabled屬性來禁用輸入框,要如何實現(xiàn)呢?一般同學(xué)會這么做
<template> <div> <el-input v-model="input" :disabled="disabled"></el-input> <div>{{errorTip}}</div> </div> </template> <script> export default { props: { //... disabled: { type: Boolean, default: false } }, //... } </script>
過一段時間后又要在myInput
組件上添加el-input
組件其它的屬性,el-input
組件總共有27個多,那該怎么呢,難道一個個用prop
傳進去,這樣做不僅可讀性差而且繁瑣,可以用$attrs
一步到位,先來看一下attrs
的定義。
$attrs: 包含了父作用域中不作為 prop
被識別 (且獲取) 的 attribute
綁定 (class
和 style
除外)。當(dāng)一個組件沒有聲明任何prop
時,這里會包含所有父作用域的綁定 (class
和 style
除外),并且可以通過 v-bind="$attrs
" 傳入內(nèi)部組件
v<template> <div> <el-input v-model="input" v-bind="$attrs"></el-input> <div>{{errorTip}}</div> </div> </template>
這還不夠,還得把inheritAttrs
選項設(shè)置為false
,為什么呢,來看一下inheritAttrs
選項的定義就明白了。
默認(rèn)情況下父作用域的不被認(rèn)作 props
的 attribute
綁定 (attribute bindings
) 將會“回退”且作為普通的 HTML attribute
應(yīng)用在子組件的根元素上。當(dāng)撰寫包裹一個目標(biāo)元素或另一個組件的組件時,這可能不會總是符合預(yù)期行為。通過設(shè)置 inheritAttrs
為 false
,這些默認(rèn)行為將會被去掉。而通過 $attrs
可以讓這些 attribute
生效,且可以通過 v-bind
顯性的綁定到非根元素上。注意:這個選項不影響 class
和 style
綁定。
簡單來說,把inheritAttrs
設(shè)置為false
,v-bind="$attrs
" 才生效。
<template> <div> <el-input v-model="input" v-bind="$attrs"></el-input> <div>{{errorTip}}</div> </div> </template> <script> export default { inheritAttrs: false, props: { value: { type: String, default: '', }, errorTip: { type: String, default: '', } }, data() { return { } }, computed: { input: { get() { return this.value }, set(val) { this.$emit('input', val) } } } } </script>
這樣就可以很清楚的把el-input
組件的屬性和myinput
組件的屬性區(qū)分開來了,組件的props
選項的可讀性大大提高。
2、$listeners
那么如何實現(xiàn)在myIpput
組件上使用el-input
組件上自定義的事件呢,可能你的第一反應(yīng)是this.$emit。
<template> <div> <el-input v-model="input" v-bind="$attrs" @blur="blur"> </el-input> <div>{{errorTip}}</div> </div> </template> <script> export default { //... methods: { blur() { this.$emit('blur') } } } </script> <myInput v-model="input" :errorTip="errorTip" @blur="handleBlur"> </myInput>
el-input
組件有4個自定義事件,還不算多,假如遇到自定義事件更多的第三方組件,要怎么辦,難道一個一個添加進去,不僅會增加一堆非必要的methods
,而且可讀性差很容易和myInput
自身的methods
混在一起。其實可以用$listeners
一步到位,先來看一下$listeners
的定義。
$listeners:包含了父作用域中的 (不含 .native
修飾器的) v-on
事件監(jiān)聽器。它可以通過 v-on="$listeners"
傳入內(nèi)部組件。
<template> <div> <el-input v-model="input" v-bind="$attrs" v-on="$listeners"> </el-input> <div>{{errorTip}}</div> </div> </template> <script> export default { //... } </script> <myInput v-model="input" :errorTip="errorTip" @blur="handleBlur"> </myInput>
在myInput
組件中只要在el-input
組件上添加v-on="$listeners
",就可以在myInput
組件上使用el-input
組件自定義的事件。
到此這篇關(guān)于關(guān)于Vue代碼可讀性的幾點建議的文章就介紹到這了,更多相關(guān)Vue代碼可讀性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3.0中給自己添加一個vue.config.js配置文件
這篇文章主要介紹了vue3.0中給自己添加一個vue.config.js配置文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07Vue報錯:TypeError:Cannot create property '
這篇文章主要介紹了Vue報錯:TypeError:Cannot create property 'xxx' on string 'xxxx'問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08關(guān)于Element-ui中table默認(rèn)選中toggleRowSelection問題
這篇文章主要介紹了關(guān)于Element-ui中table默認(rèn)選中toggleRowSelection問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08