将 `useStore` API 与 vuex 4.x 结合使用
Using `useStore` API with vuex 4.x
- 按照官方示例导出自己的
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,
}
},
- 在运行之后,
store
未定义。
- 我在
methods
属性中使用可以正常获取
methods: {
login() {
this.$store.dispatch('user/getToken')
}
}
- 为什么?如何解决
在那个 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)
在完成之前没有任何意义。
- 按照官方示例导出自己的
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,
}
},
- 在运行之后,
store
未定义。 - 我在
methods
属性中使用可以正常获取
methods: {
login() {
this.$store.dispatch('user/getToken')
}
}
- 为什么?如何解决
在那个 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)
在完成之前没有任何意义。