安装
1.安装项目选择pinia
//安装项目时直接选择Yes
√ Add Pinia for state management? ... No / Yes
2.下载
npm i pinia
在main.js中配置
import { createApp } from "vue";
//引入createPinia
import { createPinia } from "pinia";
import App from "./App.vue";
const app = createApp(App);
//调用createPinia()
const store = createPinia();
//use store
app.use(store);
app.mount("#app");
定义需要store数据,方法,getters
import { defineStore } from "pinia";
export const useCounterStore = defineStore("count", {
//数据仓库
state: () => ({
//计数
count: 0,
//购物车信息
cart: [
{ id: 1001, name: "iapd2", price: 200, num: 2 },
{ id: 1002, name: "iapd3", price: 1200, num: 12 },
{ id: 1003, name: "iapd4", price: 2300, num: 21 },
{ id: 1004, name: "iapd5", price: 2600, num: 32 },
],
token: "asdf79asd0f7a9dsf7a9ds0f",
userInfo: {
username: "admin",
password: "abcd",
},
}),
//异步方法
actions: {
jia() {
this.count++;
},
jian() {
this.count--;
},
},
//相当于计算属性
getters: {
//商品数量
goodsNum: (state) => {
let result = 0;
state.cart.forEach((item) => {
result += item.num;
});
return result;
},
//商品总价
totalPrice: (state) => {
const total = state.cart.reduce(
(acc, current) => acc + current.price * current.num,
0
);
return total;
},
//totalPrice: (state) => {},
},
});
页面使用
测试组件--{{ counterStore.count }}
商品数量:{{ counterStore.goodsNum }}
商品总价:{{ counterStore.totalPrice }}
安装依赖
npm i pinia-plugin-persistedstate
main.js中配置依赖
import { createApp } from "vue";
//引入pinia
import { createPinia } from "pinia";
//引入pinia持久化
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import App from "./App.vue";
const app = createApp(App);
//实例化pinia
const store = createPinia();
//关联pinia和pinia持久化插件
store.use(piniaPluginPersistedstate);
//app关联store
app.use(store);
app.mount("#app");
在pinia开启持久化
export const useCounterStore = defineStore("count", {
//将persist改为true,实现数据持久化
//persist: true
//或者将本地存储改为会话存储,实现数据持久化
persist: {
storage: sessionStorage,
},
});