admin管理员组

文章数量:1410730

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

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

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

use in the ponent

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
  1. Follow the official example to export your own useStore, and then use it in the ponent.
import { createStore, Store,  useStore as baseUseStore } from 'vuex';

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

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

use in the ponent

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
Share Improve this question edited Dec 14, 2020 at 1:24 Dan 63.2k18 gold badges111 silver badges119 bronze badges asked Dec 14, 2020 at 0:42 silksilk 1893 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

本文标签: javascriptUsing useStore API with vuex 4xStack Overflow