[英]Assign Keycodes to Buttons Dynamically with V-For
我的目標是復制typeform (參見問題 2)提供的鍵盤友好表單的功能。 我想使用 v-for(簡單)生成我的問題的潛在答案列表,並為每個人分配一個鍵碼,該鍵碼將一個字母綁定到每個按鈕(可能?)。
我有兩個問題:
是否可以使用 v-for 將鍵碼分配給列表? (我無法預測一個問題的可能答案數量,可能是 2+。)
以下嘗試均無效:
@keydown.:button.key :@keydown.button.key @keydown.{{button.key}}
小提琴: https : //jsfiddle.net/ffgvw3yr/5/
您可以處理您的鍵盤事件,存儲結果並在您的列表中使用處理過的鍵匹配元素索引:
<button class="query-input" type="button" v-for="(button, index) in questions.attrs" @click="answer(button.id, button.name)" :class="{ 'selected': index === selected}" >{{button.key}} {{ button.name }}</button>
您可以在掛載組件時注冊您的鍵盤事件處理函數:
methods: { processKeydown(e) { var key = 'a'; for (let i = 0; key !== 'z'; i++) { if (e.key === key) { this.$set(this, 'selected', i); break; } key = String.fromCharCode(key.charCodeAt(0) + 1); } }, }, mounted() { window.addEventListener('keydown', this.processKeydown); }, beforeDestroy() { window.removeEventListener('keydown', this.processKeydown); },
示例: JSFiddle 片段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.