【问题标题】:V-for is re-rendering all the components when a class changesV-for 是在类更改时重新渲染所有组件
【发布时间】:2020-06-18 21:45:31
【问题描述】:

我目前正在通过 moveIndex 方法和使用键事件根据图像的索引更改图像类别。我可以在计算机中顺利完成此操作,但对于电视,这需要花费太多时间。每当我使用较小的阵列时,流程都会顺利完成,但在较大的阵列中,流程会花费太多时间。这是一个可以帮助您澄清问题的代码块:

  <template>
  <div>
    <h2>Kanal Listesi</h2>
    <div class="container">
      <div>
      <div is="Channel" v-for="(channel,index) in channels" :key="index" :channel="channel"></div>
      </div>
    </div>
  </div>
</template>

<script>
import channelz from "../trsubs.channels.json";
import Channel from './Channel';
export default {
  components:{
    Channel
  },
  data() {
    return {
      channels: Object.freeze(channelz.Root.Channels.Channel),
      currentIndex: 1,
      columnNumber: 9,
      rowNumber: 7
    };
  },
    moveIndex(e) {
      var images = document.querySelectorAll("div > div > div > div > img");
      images[this.currentIndex-1]["className"] = "";
      switch (e.keyCode) {
        case 37:
          this.currentIndex =
            this.currentIndex === 1
              ? this.channels.length - 1
              : this.currentIndex - 1;
          break;
        case 38:
          this.currentIndex =
            this.currentIndex - this.columnNumber > 0
              ? (this.currentIndex -= this.columnNumber) : this.currentIndex
          break;
        case 39:
          this.currentIndex =
            this.currentIndex === this.channels.length - 1
              ? 1
              : this.currentIndex + 1;
          break;
        case 40:
          this.currentIndex =
            this.currentIndex + this.columnNumber < this.channels.length
              ? (this.currentIndex += this.columnNumber)
              : this.currentIndex;
          break;
      }
      images[this.currentIndex-1]["className"] = "selectedIndex";
    }
  }
};
</script>

这是我的频道组件:

<template>
  <div v-if="channel.ChName">
          <img :src="'http://uyanik.tv/conf/images/'+channel.Image">
    </div>
</template>

<script>
export default {
    props:['channel']
}
</script>

【问题讨论】:

    标签: javascript html arrays performance vue.js


    【解决方案1】:

    尝试使用您的频道集合中已有的唯一值:ChName 似乎是一个不错的选择。

    <div is="Channel" v-for="(channel,index) in channels" :key="channel.ChName" :channel="channel"></div>
    

    这应该有助于 vue 了解哪些发生了变化,哪些没有发生变化,并相应地重新渲染。


    另外,请避免使用 vanilla javascript 来选择 vue 中的元素。

    我指的是:

    var images = document.querySelectorAll("div > div > div > div > img");
    

    这可能应该转换为:

    var images = this.channels.map(ch => ch.Image)
    

    【讨论】:

    • 从我的 moveIndex 方法中可以看出,我正在根据它们的索引更改类,因此映射通道 Image 不会很好地工作。
    猜你喜欢
    • 2021-01-27
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2021-06-02
    • 2019-08-09
    • 2020-08-23
    相关资源
    最近更新 更多