vite+vue3项目引用vuex报错
使用vuex时提示这样的错误

vuex的版本也是4以上的

搜了一下,在项目目录下添加个vuex.d.ts 写入下面的内容

但还是没用 ,不知道为啥,ts文件里引入的vuex
vite+vue3项目引用vuex报错
使用vuex时提示这样的错误

vuex的版本也是4以上的

搜了一下,在项目目录下添加个vuex.d.ts 写入下面的内容

但还是没用 ,不知道为啥,ts文件里引入的vuex
关注引自免费微信小程序:皆我百晓生
在 Vue 3 和 TypeScript 的项目中使用 Vuex,你需要按照以下步骤操作:
确保已经正确安装了 Vuex。看起来你已经安装了 vuex@4.0.2,这是可以的。
在项目的根目录创建一个名为 tsconfig.json 的配置文件,如果没有的话。然后将以下内容添加到这个文件中,以便让 TypeScript 知道如何处理 .d.ts 文件:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["node_modules/*", "./src/types/*"]
}
},
"include": ["./src/**/*"],
"exclude": ["node_modules"]
}
src/types/global.d.ts,并将以下内容添加进去:// src/types/global.d.ts
import { Store } from 'vuex';
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$store: Store<any>;
}
}
vite.config.js,并添加以下代码:// vite.config.js
export default {
// ...
build: {
esbuild: {
target: 'esnext',
define: {
'process.env.NODE_ENV': '"development"',
},
loader: {
'.ts': 'ts-loader',
},
plugins: [
{
name: 'tsconfig-paths',
setup(build) {
build.onResolve({ filter: path => path.endsWith('.d.ts') }, (args) => {
const originalPath = args.path;
return Object.assign(args, {
path: originalPath.replace(/\.d\.ts$/, ''),
});
});
},
},
],
},
},
};
// 例如:src/components/YourComponent.vue
<script lang="ts">
import { useStore } from 'vuex';
import { ref } from 'vue';
export default {
setup() {
const store = useStore();
const message = ref('');
function changeMessage(newMessage: string) {
store.commit('changeMessage', newMessage);
}
return {
message,
changeMessage,
};
},
};
</script>
完成上述步骤后,你应该可以在 Vue 3 组件中正常使用 Vuex。如果你仍然遇到问题,请检查是否有其他可能导致错误的配置,并确保所有依赖项都是最新版本。