帶下拉選項的輸入框 (Textbox with Dropdown) 是既允許用戶從下拉列表中選擇輸入又允許用戶自由鍵入輸入值。這算是比較常見的一種 UI 元素,可以為用戶提供候選項節(jié)省操作時間,也可以給可能存在的少數(shù)情況提供適配的可能。
本來想著這個組件比較常見應(yīng)該已經(jīng)有比較多現(xiàn)成的例子可以直接應(yīng)用,但是搜索了一圈發(fā)現(xiàn)很多類似的組件都具備了太多的功能,例如搜索,多選等等 (簡單說:太復(fù)雜了!)。于是就想著還是自己動手寫一個簡單易用的,此處要感謝肥老板在我困惑時的鼎力相助。
這個 UI 元素將被用于 Common Bar Width App 中。
注冊組件
通過將封裝好的組件代碼復(fù)制粘貼來注冊全局組件。
設(shè)計的時候有考慮到輸入框可能存在不同的類型,例如文本輸入框,數(shù)值輸入框,百分數(shù)輸入框等等。所以在封裝的代碼中會通過函數(shù) inputRule
來限制輸入。限制的方法是利用 Regex 進行過濾。如果有其他類型,也可以通過修改 inputRule
中的過濾條件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<script type= "text/x-template" id= "dropdown" > <div class= "dropdown" v- if = "options" > <!-- Dropdown Input --> <input :type= "type" :disabled= "disabled" v-model= "input_value" @focus= "showOptions()" @blur= "exit()" @keyup= "keyMonitor" @input= "input_value = inputRule(type)" /> ... </script> <script> Vue.component( 'dropdown' , { template: '#dropdown' , props: { type: String, options: Array, disabled: Boolean, value: String }, ... methods: { inputRule: function (type){ var value; switch (type){ case 'text' : value = this .input_value.replace(/[^a-zA-Z0-9]/g, '' ); break ; case 'number' : value = this .input_value.replace(/^(?![+-]?\d+(\.\d+)?$)/g, '' ); break ; case 'percentage' : value = this .input_value.replace(/[^\d]/g, '' ); value = value > 100 ? '100' : value; value = value < 0 ? '0' : value; break ; default : console.log( "no limitation" ); } return value; }, ... </script> |
調(diào)用組件
添加自定義標簽調(diào)用組件。
1
2
3
4
5
6
|
<dropdown type = "text" :options = "text_options" :value = "text_value" :disabled = "text_disabled" @on_change_input_value = "onTextChange" > </dropdown> |
傳遞數(shù)據(jù)
最后動態(tài)綁定數(shù)據(jù)到父級組件, props 中:
- type: 輸入框的類型,現(xiàn)支持 text, number 和 percentage。
- options: 輸入框下拉列表的選項
- value: 輸入框的值
- disabled: 是否禁止點擊輸入框
另外我們還需要在父級實例中定義事情,用于更新輸入框的值
on_change_input_value: 更新值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
data: function () { return { text_value: 'ccc' , text_disabled: false , text_options: [ { id: 1, name: 'a' }, { id: 2, name: 'bb' }, { id: 3, name: 'ccc' }, { id: 4, name: 'dddd' }, { id: 5, name: 'eeeee' }, { id: 6, name: 'fffff ' }, { id: 7, name: 'gggggg' }, { id: 8, name: 'hhhhhhh' }, { id: 9, name: 'iiiiiiii' }, ], ... } }, ... methods: { onTextChange: function (new_text_value) { this .text_value = new_text_value; }, ... }, |
源代碼
到此這篇關(guān)于Vue.js 帶下拉選項的輸入框(Textbox with Dropdown)組件的文章就介紹到這了,更多相關(guān)Vue.js 帶下拉選項的輸入框內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/yukiwu/p/14657775.html