安装
npm install pinia
在main.ts中引入(vue3)
import { createApp } from 'vue'
import { createPinia } from "pinia";
import './style.css'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')
1.创建store文件夹,创建 index.ts 文件
import { defineStore } from "pinia";
import { Names } from "./store_name";
export const useStore = defineStore(Names.MAIN, {
state: () => {
return {
token: "",
current: "999",
};
},
// 相当于计算属性
getters: {},
// 相当于方法
actions: {
setCurrent() {
this.current = "用actions里的方法更改值";
},
},
});
2.创建 pinia 的唯一值文件 store_name.ts
export const enum Names {
MAIN = "main",
}
3.管理state的方式
// 1.直接修改
store.token = "123";
// 2.通过$patch修改
store.$patch((state) => {
state.current = "111";
});
// 3.调用acticons里的方法修改
store.setCurrent();
4.pinia 解构不具有响应式,但是可以使用storeToRefs 来让解构的state具有响应式
import { useStore } from '../store/index'
import { storeToRefs } from 'pinia'
const store = useStore()
const { current, token } = storeToRefs(store);
5.getters 和 actions
import { defineStore } from "pinia";
import { Names } from "./store_name";
type User = {
name: string;
age: number;
};
const Login = (): Promise<User> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "李子天",
age: 80,
});
}, 1000);
});
};
export const useStore = defineStore(Names.MAIN, {
state: () => {
return {
token: 1,
current: 10,
user: <User>{},
};
},
// 相当于计算属性(有缓存)
getters: {
getIntroduce(): string {
const name: string = this.user.name ?? "xxx";
const age: number = this.user.age ?? 0;
return `我是${name},我今年${age}岁了`;
},
getAge(): number {
return this.user.age;
},
},
// 相当于方法
actions: {
// 同步
setCurrent() {
this.current = 5;
},
// 异步
async setLogin() {
const res = await Login();
this.user = res;
console.log(res);
},
},
});
注意:getters里的值在页面可以用{{store.getIntroduce}}插值表达式来使用
6.api
// 监听state的api
store.$subscribe(
(args, state) => {
console.log(args, state);
},
{
detached: true, // 组件销毁之后继续监听
deep: true, // 深度监听
flush: "post", // 获取“更新之后的DOM”
}
);
// 监听actions的api
store.$onAction((args) => {
console.log(args);
}, true); // 组件销毁之后继续监听
const btn = () => {
// 重置state的api
store.$reset();
};
7.持久化
npm i pinia-plugin-persistedstate
main.ts 中引入
import { createApp } from 'vue'
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
import './style.css'
import App from './App.vue'
createApp(App).use(createPinia().use(piniaPluginPersistedstate)).mount('#app')
store文件中 index.ts 使用
import { defineStore } from "pinia";
import { Names } from "./store_name";
export const useStore1 = defineStore(Names.MAIN, {
state: () => {
return {
name: "李子天",
age: 0,
};
},
getters: {},
actions: {
setName() {
this.name = "李子天2";
},
setAge() {
this.age = 999;
},
},
// 第一种写法(持久化全部数据)
persist: true
// 第二种写法 (按需持久化数据)
persist: {
// storage: window.sessionStorage,
paths: ["name"],
},
});
export const useStore2 = defineStore(Names.ANOTHER, {
state: () => {
return {
name: "梁延涛",
};
},
getters: {},
actions: {
setName() {
this.name = "梁延涛2";
},
},
});