当导航到组件时重新计算 Computed 属性 With Getter

Re-compute Computed Property With Getter When Navigated to a Component

我将以下组件分配给 url /A

export default {

  data () {
    return {
      dummyVariableToUpdateDays: true
    }
  },

  created () {
    this.dummyVariableToUpdateDays = !this.dummyVariableToUpdateDays
  },
  computed: {
    days () {
    this.dummyVariableToUpdateDays = !this.dummyVariableToUpdateDays
      return this.$store.getters.getToDoItemsWithinRange.sort(function (a, b) {
        return new Date(b.onlyDate) - new Date(a.onlyDate)
      })
    }
  }
}

days 值是在我第一次访问此 url 时正确计算的。但是,如果我第二次访问 url A,它会再次计算,计算出的 属性 中的 getter 函数仍然给出旧值(实际上在另一个组件中已更改)。

您注意到上述行为的原因是因为 vue 不会获取对索引上的数组元素所做的更改,这已记录在案 here

When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property. Similarly, Vue.js cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is just syntax sugar for arr.splice(index, 1, value).

如上所述,您可以尝试使用:

arr.$set(index, value)

arr.splice(index, 1, value)

Further reading