我尝试使用Vuex + TypeScript并编写了简单的Vuex插件:
const cartPlugin: Plugin<RootState> = (store) => {
store.subscribe((mutation, state) => {
if (/^cart\/.+$/.test(mutation.type)) {
storage.set('cart', state.cart.cart);
}
});
};
并且TypeScript返回错误:13:33 Property 'cart' does not exist on type 'RootState'.
:
11 | store.subscribe((mutation, state) => {
12 | if (/^cart\/.+$/.test(mutation.type)) {
> 13 | storage.set('cart', state.cart.cart);
| ^
14 | }
15 | });
16 | };
但是实际上它具有属性cart(如果使用js而不是ts,则此代码有效):
const store: StoreOptions<RootState> = {
modules: {
catalog,
cart,
},
strict: true,
plugins: [cartPlugin],
};
并且模块cart
具有属性cart
:
export const state = (): CartState => {
const cart = storage.get('cart') || [];
return {
cart,
};
};
=========更新=======
我添加了RootState描述,它可以正常工作,但看起来像是临时解决方法。还是不,谁知道? :)
import { CartState } from '@/store/cart/types';
export interface RootState {
cart: CartState;
};