如何触发处理添加到 vuex 存储的新值?

How to trigger the processing of new values added to a vuex store?

我有一个存储条目的 vuex 存储:

const store = createStore({
  state() {
    return {
      entries: [
        {
          id: 1,
          date-of-birth: "2020-10-15T14:48:00.000Z",
          name: "Tom",
        },
      ],
    };
  },
});

我通过在计算 属性:

中使用 getter 获得这些条目
computed: {
  entries() {
    var entries = this.$store.getters.entries;
  }
}

出于某种原因,我想始终输出商店中最新的 date-of-birth。最初,我可以通过两种方式做到这一点:

但是,当我(通过应用程序)添加新条目时,这两种方法都不会更新 newest_date-of-birth,因为只会触发计算的 属性 entries

我尝试用两种方法解决这个问题:

所以我的问题是:在商店中添加(或从中删除)值后如何更新 newest_date-of-birth

谢谢!

您只显示了您的 vuex 对象的 state 属性。我假设您也在使用 mutation 属性 来设置内部值。

如果是这样,您所要做的就是在单个突变上设置多个状态,它们都会更新您的 computed 值,如下所示:

const store = new Vuex.Store({
  state: {
    entries: []
    lastEntrie: null
  },
  mutations: {
    addEntrie (state, entrie) {
      state.entries.push(entrie);
      state.lastEntrie = entrie;
    }
  }
})

然后,在您的 computed 值中:

computed: {
  myEntries () {
    return this.$store.state.entries
  }
  theLastEntrie () {
    return this.$store.state.lastEntrie
  }
}