Search code examples
javascriptvue-componentvuexvuejs3vue-composition-api

Using `useStore` API with vuex 4.x


  1. Follow the official example to export your own useStore, and then use it in the component.
import { createStore, Store,  useStore as baseUseStore } from 'vuex';

export const key: InjectionKey<Store<RootState>> = Symbol();

export function useStore() {
  return baseUseStore(key);
}

use in the component

setup() {
  const store = useStore();
  const onClick = () => {
    console.log(store)
    store.dispatch('user/getUserInfo');
  }
  return {
    onClick,
  }
},
  1. After running, store is undefined.
  2. It can be obtained normally when I use it in the methods attribute
methods: {
  login() {
    this.$store.dispatch('user/getToken')
  }
}
  1. why? how to fix it

Solution

  • In that simplifying useStore usage tutorial, you still need to register the store and key in main.ts as they did. You will get undefined if you don't do this:

    // main.ts
    import { store, key } from './store'
    
    const app = createApp({ ... })
    
    // pass the injection key
    app.use(store, key)
    

    The reason is that baseUseStore(key) has no meaning until that's done.