2017-05-05 83 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