如何禁用Vuex getter的缓存?是否支持类似Vue计算属性的cache:false配置
Great question! To cut to the chase: Vuex getters do NOT support the cache: false option that’s available for Vue component computed properties.
Why is that?
Vuex getters are built around reactive dependency tracking with built-in caching. A getter will only re-calculate its value when the specific pieces of state it relies on change. Unlike component computed properties (which added the cache: false option in Vue 3.2+ to opt out of this behavior), Vuex has no native configuration to disable this caching mechanism for getters—this is intentional, as getters are designed to efficiently return derived state based on reactive dependencies.
Workarounds for "non-cached" getter-like behavior
If you need a value that recalculates every time you access it (instead of only when state changes), here are a few practical alternatives:
Return a function from the getter
Define a getter that returns a function, which will execute fresh logic each time you call it:// In your Vuex store const store = createStore({ state: {}, getters: { now: () => () => { return Date.now(); } } });Then in your component, call it like a function to get a fresh value:
this.$store.getters.now(); // Returns current timestamp every invocationUse a component method or non-cached computed property
If the logic doesn’t need to be shared across components, skip the Vuex getter entirely. Either use a component method that runs the calculation on demand, or a Vue 3+ computed property withcache: false:// In your Vue component (Vue 3 setup syntax) import { computed } from 'vue'; export default { setup() { const now = computed(() => Date.now(), { cache: false }); return { now }; } };Use a Vuex action (for async logic)
If your non-cached value requires async operations (like fetching fresh data from an API), an action is the right tool. Dispatch it whenever you need a fresh result:// In your Vuex store const store = createStore({ actions: { fetchFreshTimestamp() { // Example async logic—replace with your own return new Promise(resolve => { setTimeout(() => resolve(Date.now()), 100); }); } } });Then in your component:
const freshTimestamp = await this.$store.dispatch('fetchFreshTimestamp');
Key Takeaway
Vuex getters are optimized for reactive, cached derived state. If you need non-cached calculations, use one of the workarounds above instead of trying to modify getter caching behavior directly.
内容的提问来源于stack exchange,提问作者feihcsim

