2017-05-05 42 views
0

考慮到與data.selected=[i,j],並用​​事件偵聽器表以改變箭頭導航基於鍵盤箭頭,如何以及在何處插入表達if (i===selected[0] && j = selected[1]) node.focus()協調?如何實現表苗條

<table on:keydown='arrow(event.keyCode)'> 
    {{#each rows as row, i}} 
    <tr> 
    {{#each row as val, j}} 
    <td tabIndex=1>{{val}}</td> 
    {{/each}} 
    </tr> 
    {{/each}} 
</table> 

主要處理程序可以改變selected指數,但沒有到節點自身的引用。

我試着插入模板中的表達式,並在if block但我得到的錯誤。

回答

1

我可能會做這樣的事情 - 把對細胞本身的數據屬性,然後用querySelector找到節點調用.focus()上。

Here's a demo in the REPL

<table ref:table> 
    {{#each rows as row, i}} 
    <tr> 
     {{#each row as val, j}} 
     <td tabIndex=1> 
     <input 
      data-row='{{i}}' 
      data-col='{{j}}' 
      on:keydown='arrow(this, event.keyCode)' 
      on:focus='set({selected: [i, j] })' 
      bind:value='val'> 
     </td> 
     {{/each}} 
    </tr> 
    {{/each}} 
</table> 

<script> 
    export default { 
    oncreate() { 
     this.observe('selected', s => { 
     this.refs.table.querySelector(`[data-row="${s[0]}"][data-col="${s[1]}"]`).focus(); 
     }); 
    }, 
    methods: { 
     arrow (node, code) { 
     if (code < 37 || code > 40) return; 

     let i = +node.dataset.row; 
     let j = +node.dataset.col; 

     const rows = this.get('rows'); 
     const row = rows[i]; 

     if (code === 37) j = Math.max(0, j - 1); 
     if (code === 39) j = Math.min(j + 1, row.length - 1); 
     if (code === 38) i = Math.max(0, i - 1); 
     if (code === 40) i = Math.min(i + 1, rows.length - 1); 

     this.set({ selected: [ i, j ] }); 
     } 
    } 
    }; 
</script> 
+0

甜。完美的作品。對我來說絕對不是顯而易見的。 – Hurelu