1.pinia.ts 定义
import { defineStore } from "pinia";
import { Names } from "./store-name";
import { ref, computed } from "vue";
import Dayjs from "dayjs";
export const useTestStore = defineStore(Names.TEST, {
state: () => ({
name: "多多",
count: 1,
time: [Dayjs(new Date()).format("YYYY-MM-DD")]
}),
getters: {
double: (state) => state.count * 2
},
actions: {
increment() {
this.count++;
},
changeTime(value: string[]) {
this.time = value;
}
}
});
interface User {
name: string;
age: number;
}
const asyncData = () => {
return new Promise<User>((resolve, reject) => {
setTimeout(() => {
resolve({ name: "异步", age: 2000 });
}, 2000);
});
};
export const useUserStore = defineStore(Names.USER, () => {
const name = ref("图图");
const age = ref(18);
const userMsg = computed(() => {
return `我叫${name.value},我${age.value}岁了`;
});
const setUser = (user: User) => {
!!user.name && (name.value = user.name);
!!user.age && (age.value = user.age);
};
const asyncSetUser = async () => {
const res = await asyncData();
setUser(res);
};
return { name, age, userMsg, setUser, asyncSetUser };
});
2.使用
<div>USER:{{ name }} --- {{ age }} --- {{ userMsg }}</div>
<div>
TEST:
<el-button type="primary" :icon="Edit" circle @click="test.increment" />
count:{{ test.time }}{{ test.count }}double:{{ test.double }}
</div>
import { useUserStore, useTestStore } from "@/store/pinia";
import { storeToRefs } from "pinia";
const user = useUserStore();
const test = useTestStore();
const { name, age,userMsg } = storeToRefs(user);