Vue AutoComplete Example

WilliamAndChill Liu
Nov 3 · 3 min read

AutoComplete: 輸入文字後自動查詢關鍵字符合的內容,選擇後自動填寫

先達成這個效果吧,先把Html畫出來,之後寫一隻Vue.js 去Binding處理達成自動查詢這個功能

datas: 這邊我放了一些要查詢國家比對的名稱

searchValue: 查詢的關鍵字

results: 結果;也就是查詢後,有匹配關鍵字的國家名稱

isOpen: 是否要打開顯示出現結果選項

說明一下怎麼運作

主要是透過Watch去監控 searchValue 查詢文字的變更,一有變更就觸發 filterResults 事件去查詢結果,這邊使用indexOf 去比對文字如果有關鍵字符合就會>-1。


再來還有一個主要功能要達成

我想要將選到的選項自動填寫至我的輸入框

  1. 在做選擇時,希望透過鍵盤上的 up,down,enter,esc 去做效果的呈現
  2. 當然也要能透過滑鼠的移動去選擇到我想要的選項

currentlyCounter:這個屬性用來控制我在結果(results)集合內選項選到第幾個位置,預設-1代表我尚未選擇。

*注意到我在js檔案上寫了 Vue.config.keyCodes,這邊設定的keycode是按鍵的鍵碼。

鍵盤鍵碼值對照表

以Vue.config.keyCodes.up = 38 舉例,鍵盤的"上"鍵(鍵碼38)設定在 Vue.config.keyCodes.up ,我透過HTML的input掛上v-on:keydown.up去觸發"onArrowUp"事件,達到選擇選項的效果。

結語:本篇文章練習到了,可以透過keyCodes去抓鍵盤上的按鍵是否觸發,還有要小心比對英文字的時候,要不要將關鍵字與比對文字都做LowerCase的處理,看需求再來做程式上的處理。

Github程式碼連結

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade