Vue3+TS项目pinia使用优化在stores目录下新建index.ts
前言
能减少一些重复的代码吧
步骤
假设stores目录下有project.ts、user.ts两个文件
project.ts
import { defineStore } from 'pinia'export default defineStore('project', () => {// ...
})
user.ts
import { defineStore } from 'pinia'export const useUserStore = defineStore('user', () => {// ...
})
如果一个页面中需要使用project.ts和user.ts中的数据时,要编写以下代码,如果还用到其它的store文件,要import的就更多了。不同的页面,这段代码会一直重复写。
import useProjectStore from './project'; // export default导出的不加{}
import { useUserStore } from './user'; // export导出的需要加{}且命名一致const projectStore = useProjectStore();
const userStore = useUserStore();// 使用变量 projectStore.xxxx
// 调用方法 userStore.yyyy()
优化:在stores目录下新建一个index.ts,将store文件统一导出。代码如下:
import useProjectStore from './project';
import { useUserStore } from './user';const projectStore = useProjectStore();
const userStore = useUserStore();export { projectStore, userStore };
这个时候页面使用时,只需要写一行导入代码,我觉得算是优化了很多
import { projectStore, userStore } from '@/stores/index';// projectStore.xxx
// userStore.yyyy()