Search code examples
vuejs2vuexvue-composition-apivue-script-setup

How to export reactive Vuex state from setup in Vue2.7


Here's a reproduction link: https://stackblitz.com/edit/node-c6mn17?file=src/components/Test.vue

I want to be able to use reactive state from that store using setup in Vue 2.7.

I export a Vuex store using export const store = new Vuex.Store({ ... })

Both of these fail:

const count1 = store.state.count;
const count2 = ref(store.state.count);

Doesn't work when exporting the store as a function either: export const useStore = () => store and doing useStore().state ...


Solution

  • Or toRef/toRefs

    const { count } = toRefs(store.state);
    const count1 = toRef(store.state, "count");
    

    Stackblitz