1

data.selected=[i,j]给定一个带有事件侦听器的表格,keydown以根据键盘箭头更改坐标,如何以及在何处插入表达式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但我得到了错误。

4

1 回答 1

3

我可能会这样做——将数据属性放在单元格本身上,然后用于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>
于 2017-05-05T13:24:51.207 回答