之前一直想寫一篇關(guān)于抽象 Vue 組件的隨筆,無奈一直沒想到好的例子。恰巧最近為公司項目做了一個數(shù)字鍵盤的組件,于是就以這個為例聊聊如何抽象 Vue 的組件。
先上 Demo 與 源碼。(demo最好在瀏覽器里以手機模式瀏覽)
在講具體實現(xiàn)前,我想先分享下自己認為的理想的公用組件是什么樣的:
1. 黑盒性,即除了你自己以外,其他的開發(fā)者在快速閱讀使用文檔之后可以立刻上手,而不用關(guān)心你的內(nèi)部實現(xiàn);
2. 獨立性,即做好解耦,不與父組件有過多關(guān)聯(lián);
3 自定義性,適當(dāng)?shù)乇┞兑恍┹斎虢涌诨蛘叻椒ńo外部用于自定義,同時也要設(shè)置好這些屬性在外部未輸入時的默認值。
下面我們先以黑盒的方式看看 demo 中數(shù)字鍵盤組件是如何調(diào)用的(已省略非關(guān)鍵部分代碼)。
App.vue
<template> ...... <keyboard @submit-event='handleSubmit' @change-event='handleChange'></keyboard> </template> <script> import keyboard from 'Keyboard.vue'; export default { data() { return { value: '' }; }, methods: { handleChange(value, currentValue) { console.log(value, currentValue); this.value = value; }, handleSubmit() { console.log('submit: ' + this.value); } } } </script>
如上,最基本的調(diào)用就完成了。效果如下:
接著,點擊 1-6 與“確定”。如果如下:
可以看到數(shù)字鍵盤已經(jīng)如我們預(yù)期工作了,接下來分析下該數(shù)字鍵盤組件所有的輸入項。
@change-event:該事件為自定義事件,父組件通過 v-on 注冊監(jiān)聽,子組件內(nèi)部通過 $emit 進行觸發(fā)(更多自定義事件相關(guān)內(nèi)容請參考:Vue官方教程)。
每一次點擊數(shù)字按鍵以及退格鍵均會觸發(fā)該事件,其傳遞兩個參數(shù):value,累積點擊的字符組合;currentValue,當(dāng)前點擊的字符。父組件通過 handleChange 方法接收該事件的回調(diào)內(nèi)容。
@submit-event:當(dāng)點擊“確定”鍵即會觸發(fā)該事件,其不傳遞參數(shù),只是告訴父組件“我的確定按鈕被點擊了,你要做什么操作自己看著辦吧,之前點擊的數(shù)字已經(jīng)通過 change-event 傳給你了”。父組件通過 handleSubmit 方法接收回調(diào)。
如果只寫這兩個方法未免也太沒誠意了,我還根據(jù)一些場景編寫了以下幾個自定義屬性。
max:最大輸入長度,超過的部分將不會觸發(fā) change-event 事件,默認無限制。
<keyboard max='6'></keyboard>
sp-key:自定義的特殊字符,如身份證輸入時的“X”,會添加到左下角空白格,默認無。
<keyboard sp-key='X'></keyboard>
random:是否打亂數(shù)字順序,一些有關(guān)銀行賬戶或密碼的輸入經(jīng)常會見到這種場景,默認 false。
<keyboard random='true'></keyboard>
從上面的幾個自定義屬性與事件,我們大概知道了父組件是如何向子組件傳值以及監(jiān)聽子組件的變化,但父組件該如何直接調(diào)用子組件內(nèi)部的函數(shù)呢?我們看下面這個場景。
數(shù)字鍵盤上的鍵盤圖標,點擊之后會將數(shù)字鍵盤收起隱藏。組件內(nèi)部擁有一個方法 keyboardToggle(true|false) 來控制鍵盤的彈起和收回,那么如果在組件外部也想調(diào)用這個方法呢?比如當(dāng)父組件中的 input 獲取到焦點時。
可以通過 Vue 中的 ref 屬性來獲取到鍵盤的組件引用,從而調(diào)用其內(nèi)部的方法,如下:
$refs.[refName].keyboardToggle(true|false)
<template> <input type='text' @focus='handleShowKeyboard($event)' /> <keyboard ref='kbref'></keyboard> </template> <script> import keyboard from 'Keyboard'; export default { //... methods: { handleShowKeyboard(e) { e && e.preventDefault(); this.$refs.kbref.keyboardToggle(true); } } } </script>
以上面這種形式便可以在父組件上下文中調(diào)用子組件內(nèi)的方法。
$refs.[refName].handleInit()
數(shù)字鍵盤組件內(nèi)部的初始化方法,用于重新渲染組件。若 random 屬性為 true,則數(shù)字鍵會刷新隨機排列。
$refs.[refName].handleClear()
清除之前輸入的字符組合,并觸發(fā) change-event 且返回空字符串。
上面分享了這個組件所有對外的屬性與事件,可以發(fā)現(xiàn)我們并未看過該組件內(nèi)部的一行代碼,但已經(jīng)可以完整的使用它了,下面來聊聊內(nèi)部實現(xiàn)。
首先來看看布局,我將鍵盤分為左右兩部分,右邊部分不用多說,左邊的部分是將一個鍵位數(shù)組通過 v-for 循環(huán)生成。
那么是如何讓 0 和 9 之間空出一格呢,下面看下初始化鍵盤組件的方法。
keyboard.vue
handleInit()
<template> <div> <div class='kb-left'> <div class='kb-item' v-for='item in keyArr'>{{item}}</div> <div class='kb-item kb-toggle'></div> //鍵盤圖標 </div> <div class='kb-right'> //... </div> </div> </template> <script> export default { data() { return { baseArr: [] } }, computed: { keyArr() { this.handleInit(); return this.baseArr; } }, methods: { handleInit() { this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; this.baseArr.splice(this.baseArr.length - 1, 0, ''); } } } </script>
即在鍵位數(shù)組倒數(shù)第二位插入一個空字符,然后循環(huán)生成按鍵。下面看下自定義參數(shù)是如何生效的。
sp-key
<script> export default { props: ['spKey'], data() { return { baseArr: [] } }, //.... methods: { handleInit() { let spKey = this.spKey; this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; this.baseArr.splice(this.baseArr.length - 1, 0, spKey); } } } </script>
在組件內(nèi)部通過 props 屬性接收父組件傳遞的 spKey,之后就可在組件內(nèi)的屬性和方法中通過 this.spKey 進行訪問。首先判斷 spKey 值是否有效,并代替空字符插入鍵位數(shù)組倒數(shù)第二項。
random
<script> export default { props: ['spKey', 'random'], data() { return { baseArr: [] } }, //.... methods: { handleInit() { let spKey = this.spKey; this.baseArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']; if (this.random && this.random != 'false') { this.baseArr.sort(function() { return Math.random() - Math.random(); }); } this.baseArr.splice(this.baseArr.length - 1, 0, spKey); } } } </script>
將鍵位打亂順序其實也很簡單,只要通過數(shù)組的 sort 方法。sort 方法可以接收一個函數(shù)作為參數(shù),若函數(shù)返回正數(shù)則交換前后兩項的位置,若函數(shù)返回負數(shù)則不作交換。所以將兩個隨機數(shù)相減的結(jié)果返回,即可將鍵位數(shù)組隨機排序。
下面看看在組件內(nèi)部是如何觸發(fā) change-event 的。
handleInput()
<template> <div> <div class='kb-left'> <div @click='handleInput(item)' class='kb-item' v-for='item in keyArr'>{{item}}</div> <div class='kb-item kb-toggle'></div> //鍵盤圖標 </div> //... </div> </template> <script> export default { data() { return { inputStr: '' } }, //... methods: { handleInput(value) { this.inputStr += value; this.$emit('change-event', this.inputStr, value); } } } </script>
增加了 max 屬性后修改方法如下:
handleInput(value) { let max = Number(this.max); if (!isNaN(max) && this.inputStr.length+1 > max) { return; } this.inputStr += value; this.$emit('change-event', this.inputStr, value); }
最后看看退格刪除是如何實現(xiàn)的。
handleDelete()
handleDelete() { let str = this.inputStr; if (!str.length) return; this.inputStr = str.substring(0, str.length - 1); this.$emit('change-event', this.inputStr); }
上面的例子都是些核心代碼的片段,并且其他輔助函數(shù)并未列出,想查看完整的代碼請看源碼。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com