简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM