export let useProductsStore = defineStore('products', () => {
let data = ref(products);
function getList (params) {
return someSearchStuffForProducts(params);
}
return {data, getList};
});
然后可以用作:
let productsStore = useProductsStore();
console.log(data, data.value);
productsStore.getList(params);
我们可以创建多个商店:
let usersStore = useUsersStore();
let productsStore = useProductsStore();
let basketStore = useBasketStore();
let favoritesStore = useFavoritesStore();
商店可以互相引用:
export let useUsersStore = defineStore('users', () => {
let productsStore = useProductsStore();
}
export let useBasketsStore = defineStore('basket', () => {
let productsStore = useProductsStore();
}
//Et cetera
最后,Pinia/Vuex 是提供检索和操作存储在状态中的数据的能力的工具。
经理/服务类
但还有另一种成熟的方法:管理器/服务类。
前面的例子可以重写为:
//Define the "single source of truth"
let store = {
products: { /* ... */},
currentUser: { /* ... */},
userBasket: { /* ... */},
userFavorites: { /* ... */},
};
//Here goes manager classes
class ProductsManager {
constructor (params) {
this.state = params.state;
//...
}
getList (params) {
return someSearchStuffForProducts(params);
}
}
class UsersManager {
constructor (params) {
this.state = params.state;
//Products manager is injected as a dependency
this.productsManager = params.productsManager;
//...
}
}
class BasketManager {
constructor (params) {
this.state = params.state;
//Products manager is injected as a dependency
this.productsManager = params.productsManager;
//...
}
}
//Some config/initialization script
export let DIC = {}; //Container for manager instances
DIC.productsManager = new ProductsManager({state: store.products});
DIC.usersManager = new usersManager({
state: store.currentUser,
productsManager: DIC.productsManager,
});
DIC.basketManager = new BasketManager({
state: store.userBasket,
productsManager: DIC.productsManager,
});
//Usage
import {DIC} from './config';
DIC.productsManager.getList();
DIC.basketManager.add(someProductId);
DIC.basketManager.changeCount(someProductId, 3);