我可能会这样做——将数据属性放在单元格本身上,然后用于querySelector
查找要调用的节点.focus()
。
这是 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>