为什么数组中的该值无法在vue.js模板中更新?

时间:2019-09-24 18:37:03

标签: javascript vue.js

因此,我在数组中有一个持续时间值,该值通过使用setInterval调用每毫秒计算持续时间的方法进行更新。

问题是我无法显示此值,更不用说在模板中更新了。这是我的vue.js代码的一个片段

  data() {
    return {
      job_execs: [],
      stageMatrix: [],
      liveStageDuration: {},
    }
  },
  mounted() {
    // Updates current job duration every second
    let that = this;
    setInterval(that.updateLive, 50);
  },
  methods: {
    updateLive: function() {
      // Calculate current job duration
      for (let parent = 0; parent < this.stageMatrix.length; parent++) {
        for (let item = 0; item < this.stageMatrix[parent].length; item++) {
          if (this.stageMatrix[parent][item].status.name === "IN_PROGRESS") {
            let parentId = null
            let newDuration = liveDurationMs(this.stageMatrix[parent][item].time_start)
            if (this.stageMatrix[parent][item].stage_execution_parent != null) {
              parentId = this.stageMatrix[parent][item].stage_execution_parent.name
            }
            else {
              parentId = 'none1'
            }
            this.liveStageDuration[parentId] = newDuration
            console.log(this.liveStageDuration[parentId])
          }
        }
      }
      return true
    }, 

摘要模板:

<table class="hideTable">
  <tbody>
    <template v-for="row in stageMatrix">
      <tr :key="row.id">
        <template v-for="col in row">
          <template v-if="col === undefined">
            <td
              :key="col"
              class="hideCell" />
          </template>
          <template v-else>
            <td
              :key="col.id"
              :class="col.status.name"
              :title="getExecNode(col)">
              <b>
                <template v-if="col.time_end === 'N/A'">
                  {{ col.stage.name }}
                </template>
                <template v-else>
                  <a
                    :href="job_execs[0].mongo_link + col.stage.name + '.txt'">
                    {{ col.stage.name }}
                  </a>
                </template>
              </b>
              <br>
              <template v-if="col.status.name === 'IN_PROGRESS'">
                {{ liveStageDuration.none1 }}
              </template>
              <template v-else>
                {{ changeDuration(col.duration_millis) }}
              </template>
              <br>
              {{ col.status.name }}
            </td>
          </template>
        </template>
      </tr>
    </template>
  </tbody>
</table>

如果我要在数据下设置liveStageDuration:null,然后像这样在updateLive中为其指定持续​​时间

this.liveStageDuration = newDuration

,然后从模板调用liveStageDuration:

{{ liveStageDuration }}

持续时间将显示并按预期更新。因此,我的对象或数组出了点问题,或者模板看不到这些对象内进行的更新。我真的不确定。

1 个答案:

答案 0 :(得分:1)

同样由于现代JavaScript的限制,Vue无法检测到属性的添加或删除。

  

例如:

     
   this.$set(this.someObject, 'property', value)
  

因此

  

正确的代码

     
   this.$set(this.liveStageDuration, 'parentId', newDuration)
  

参考 https://vuejs.org/v2/guide/list.html#Caveats