如何触发处理添加到 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
- 通过简单地添加一个新的
data
变量 newest_date-of-birth
,该变量在(例如)beforeMounted
挂钩中设置。
但是,当我(通过应用程序)添加新条目时,这两种方法都不会更新 newest_date-of-birth
,因为只会触发计算的 属性 entries
。
我尝试用两种方法解决这个问题:
- 当我尝试在计算的范围内更新
newest_date-of-birth
属性 entries
,我被建议不要这样做,因为它似乎是
不好的做法(计算属性中没有副作用)。
- 另外
watch
过度计算 属性 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
}
}
我有一个存储条目的 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
- 通过简单地添加一个新的
data
变量newest_date-of-birth
,该变量在(例如)beforeMounted
挂钩中设置。
但是,当我(通过应用程序)添加新条目时,这两种方法都不会更新 newest_date-of-birth
,因为只会触发计算的 属性 entries
。
我尝试用两种方法解决这个问题:
- 当我尝试在计算的范围内更新
newest_date-of-birth
属性entries
,我被建议不要这样做,因为它似乎是 不好的做法(计算属性中没有副作用)。 - 另外
watch
过度计算 属性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
}
}