【问题标题】:Using `useStore` API with vuex 4.x在 vuex 4.x 中使用`useStore` API
【发布时间】:2021-03-24 16:40:00
【问题描述】:
  1. 按照官方示例导出自己的useStore,然后在组件中使用。
import { createStore, Store,  useStore as baseUseStore } from 'vuex';

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

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

在组件中使用

setup() {
  const store = useStore();
  const onClick = () => {
    console.log(store)
    store.dispatch('user/getUserInfo');
  }
  return {
    onClick,
  }
},
  1. 运行后,store 未定义。
  2. 我在methods属性中使用时可以正常获取
methods: {
  login() {
    this.$store.dispatch('user/getToken')
  }
}
  1. 为什么?如何解决它

【问题讨论】:

    标签: javascript vue-component vuex vuejs3 vue-composition-api


    【解决方案1】:

    在那个simplifying useStore usage 教程中,您仍然需要像他们一样在main.ts 中注册store 和key。如果你不这样做,你会得到 undefined:

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

    原因是baseUseStore(key) 在完成之前没有任何意义。

    【讨论】:

      猜你喜欢
      • 2023-02-10
      • 1970-01-01
      • 2022-01-02
      • 2020-11-22
      • 1970-01-01
      • 2016-10-03
      • 2018-04-06
      • 2018-03-14
      • 2018-03-19
      相关资源
      最近更新 更多