1. 安装依赖
pnpm i pinia
2. 在main.js中引入pinia
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { createPinia } from "pinia";
const app = createApp(App);
app.use(createPinia());
app.mount("#app");
3. src下新建store文件夹,counter.js文件
import { defineStore } from "pinia";
export const useCounter = defineStore("counter", {
state: () => {
return {
count: 0,
};
},
getters: {
dobuleCount: (state) => {
return state.count * 2;
},
},
actions: {
incrementAsync() {
setTimeout(() => {
this.count++;
}, 1000);
},
setCount(val) {
this.count = val;
},
},
});
4. vue文件使用
<script setup>
import { storeToRefs } from "pinia";
import { useCounter } from "./store/counter";
const counter = useCounter();
const { count, dobuleCount } = storeToRefs(counter);
const addCount = (val) => {
counter.$patch({
count: counter.count + val,
});
};
const reset = () => {
counter.$reset();
};
</script>
<template>
<div>
<p>{{ count }}</p>
<p>{{ dobuleCount }}</p>
<button @click="counter.incrementAsync()">count++</button>
<button @click="counter.setCount(10)">setCount</button>
<button @click="addCount(10)">count+10</button>
<button @click="reset">重置</button>
</div>
</template>