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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值