选择式写法
一、安装pinia依赖
终端输入:npm install pinia
二、配置pinia
第一步:创建仓库,在src目录下创建文件夹modules和文件index.ts.
第二步:配置index.ts
// 创建pinia大仓库
import { createPinia } from "pinia";
let store = createPinia();
export default store;
第三步:在main.ts引入
第四步(案例):配置小仓库info
import { defineStore } from "pinia";
// defineStore("仓库名","仓库的基础配置")
let useInfoStore = defineStore("info", {
// 存储数据
state: () => {
return {
name: "zs",
age: 1,
};
},
actions: {
changeAge() {
this.age++;
},
},
getters: {
c() {
let s: string = this.name + this.age;
return s;
},
},
});
export default useInfoStore;
第五步:组件调用小参考数据
组合式写法
import { defineStore } from "pinia";
import { ref, computed } from "vue";
let useToolStore = defineStore("tool", () => {
let tool = ref([
{ name: "lisi", age: 12 },
{ name: "wangwu", age: 14 },
]);
let arr = ref([1,2,3]);
const c = computed(() => {
return arr.value.reduce((pre: any, next: any) => {
return pre + next;
},0);
});
return {
tool,
arr,
updateAge() {
tool.value.push({ name: "xx", age: 66 });
},
c,
};
});
export default useToolStore;