// 设置全局唯一Id const useStore = defineStore("storeId", { // arrow function recommended for full type inference state: () => { return { // all these properties will have their type inferred automatically counter: 0, name: "Eduardo", isAdmin: true }; } });
// 当someStore的action有调用的时候进行监听 const unsubscribe = someStore.$onAction( ({ name, // name of the action store, // store instance, same as `someStore` args, // array of parameters passed to the action after, // hook after the action returns or resolves onError // hook if the action throws or rejects }) => { // a shared variable for this specific action call const startTime = Date.now(); // this will trigger before an action on `store` is executed console.log(`Start "${name}" with params [${args.join(", ")}].`);
// this will trigger if the action succeeds and after it has fully run. // it waits for any returned promised after((result) => { console.log(`Finished "${name}" after ${Date.now() - startTime}ms.\nResult: ${result}.`); });
// this will trigger if the action throws or returns a promise that rejects onError((error) => { console.warn(`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`); }); } );
// add a property named `secret` to every store that is created after this plugin is installed // this could be in a different file functionSecretPiniaPlugin() { return { secret: "the cake is a lie" }; }
const pinia = createPinia(); // give the plugin to pinia pinia.use(SecretPiniaPlugin);
// 注意:增加的options需要和actions,state平级 debounce: { // debounce the action searchContacts by 300ms searchContacts: 300 } });
// lodash库 import debounce from"lodash/debunce";
// 给全局增加方法拦截,只要有debounce对象所对应的action都debounce pinia.use(({ options, store }) => { if (options.debounce) { // we are overriding the actions with new ones returnObject.keys(options.debounce).reduce((debouncedActions, action) => { debouncedActions[action] = debounce(store[action], options.debounce[action]); return debouncedActions; }, {}); } });