先创建stores文件夹,内部创建index.js文件和各分类文件
main.js文件内部
import pinia from "./stores";
app.use(pinia);
stores文件夹内index.js文件内部
import { createPinia } from "pinia";
const pinia = createPinia();
export default pinia;
stores文件夹内分类仓库文件内部(counter.js文件)
import { defineStore } from "pinia";
import useUser from "./user";
const useCounter = defineStore("counter", {
state: () => ({
count: 99,
friends: [
{ id: 111, name: "why" },
{ id: 112, name: "kobe" },
{ id: 113, name: "james" },
],
banners: [],
}),
getters: {
doubleCount(state) {
return state.count * 2;
},
doubleCountAddOne() {
return this.doubleCount + 1;
},
getFriendById(state) {
return function (id) {
for (let i = 0; i < state.friends.length; i++) {
const friend = state.friends[i];
if (friend.id === id) {
return friend;
}
}
};
},
showMessage(state) {
const userStore = useUser();
return `name:${userStore.name}-count:${state.count}`;
},
},
actions: {
async fetchHomeMultidata() {
const res = await fetch("http://123.207.32.32:800/home/mutidata");
const data = await res.json();
this.banners = data.data.banner.list;
},
},
});
export default useCounter;
使用
<script setup>
import { toRefs } from "vue";
import { storeToRefs } from "pinia";
import useCounter from "./stores/counter";
const counterStore = useCounter();
const { count } = toRefs(counterStore);
const { count } = storeToRefs(counterStore);
function changeState() {
counterStore.count = 100;
counterStore.$patch({
count: 99,
});
}
function resetState() {
counterStore.$reset();
}
counterStore.fetchHomeMultidata();
</script>
<template>
//state调用
//可以直接写仓库内变量名获取
<div>{{ counterStore.count }}</div>
//在js中解构出来直接使用
<div>{{ count }}</div>
//修改/重置state
<button @click="changeState">修改</button>
<button @click="resetState">重置</button>
//getters调用
<h2>doubleCount:{{ counterStore.doubleCount }}</h2>
<h2>doubleCountAddOne:{{ counterStore.doubleCountAddOne }}</h2>
<h2>friend-111:{{ counterStore.getFriendById(111) }}</h2>
<h2>showMessage:{{ counterStore.showMessage }}</h2>
</template>