一、简介
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
二、安装
npm install pinia
在main.js中创建实例
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)app.use(pinia)
app.mount('#app')
三、基本使用
1.创建一个文件,store/storeIndex.ts
2.创建一个叫做counter的仓库并在里面定义响应式数据或者函数,和在<script setup>中类似
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useCounterStore = defineStore("counter", () => {const count = ref(0);const doubleCount = computed(() => count.value * 2);function increment() {count.value++;}return { count, doubleCount, increment };
});
3.使用
<div class="card"><button type="button" @click="increment">count is {{ count }}</button></div>
<script setup lang="ts">
import { useCounterStore } from "../store/storeIndex";
import { storeToRefs } from "pinia";
const store = useCounterStore();
const { count } = storeToRefs(store);
const { increment } = store;
</script>
四、简单体验
可以在通过下面的模板体验一下基础的pinia使用
Vite+Vue3+TS+Vue-Router+Axios+Pinia开发模板-CSDN博客
五、更多信息
Pinia | The intuitive store for Vue.js