【问题标题】:Vue js input in table row inside v-ifVue js在v-if内的表格行中输入
【发布时间】:2021-06-08 16:39:33
【问题描述】:

我有这种情况:

  • 创建表中所有行的 v-for
  • 一个 v-if 决定该行是否可见

在这个fiddle 中,我创建了一个示例。

如果我仅在一个输入中更改值,则对所有行重新执行 v-if(在 v-if 方法中检查大量数据时,当用户输入输入时会减慢很多.)

我的问题是它为所有行重新执行 v-if,但我只需要为当前行执行它。有什么解决办法吗?我认为这是 Vue 的正常行为,但在 v-if 上使用繁重的方法,用户被阻止(图像他在输入中键入 3 个字母,表格有 100 行,这意味着 v 内的方法执行 300 次- 如果在视觉上我们可以看到输入工作缓慢)

    <div id="app">
      <table class="table table-striped">
      <thead>
        <tr>
          <th>#</th>
          <th>input</th>
          <th>2018</th>
          <th>2017</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(sale,i) in sales[0]" :key="i" v-if="isItemGood(sale)">
           <th scope="row">{{ sale.Month  }}</th>  
           <td><input v-model="asd"></input></td>
           <td>{{ sale.Sale }}</td>
           <td>{{ sales[1][i].Sale }}</td>  
        </tr>
       </tbody>
    </table>
    </div>
    
    new Vue({
      el: "#app",
      data: {
        asd: null,
        sales: [
            [{'Year': 2018, 'Month': 01, 'Sale': 512}, {'Year': 2018, 'Month': 02, 'Sale': 1025}],
                [{'Year': 2017, 'Month': 01, 'Sale': 155}, {'Year': 2017, 'Month': 02, 'Sale': 12}]
        ]
      },
      methods: {
        isItemGood(sale) {
          console.log(sale)
          return true
        }
      },
      watch: {
        asd: {
          handler(newValues) {
          }
        }
      }
    })
    <style>
    td, th { border: 1px solid red;}
    </style>

【问题讨论】:

标签: javascript vue.js vuejs2 bootstrap-table


【解决方案1】:

首先,我建议你使用一个计算方法来返回过滤后的数组

computed: {
  filteredSales() {
    return this.sales[0].filter(this.isItemGood);
  }
}

然后通过计算数组迭代 v-for。

另一件可能会加快速度的事情是使用 v-show 而不是 v-if(它不会真正重新渲染),但请记住,这将渲染项目,但不会使它们可见

【讨论】:

  • 问题是每一行都应该有它自己的计算(例如隐藏第 1 行,显示第 2 行,隐藏第 3 行,我认为将参数传递给计算方法不是一个好主意)
猜你喜欢
  • 2021-11-10
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 2023-02-08
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多