1. 导入
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(createPinia()).mount('#app')
2. 创建
defineStore() 第一个参数是仓库名 ,用作 id 。devtools 用来区分哪个仓库。这里例子用组合式写法。
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useCounterStore = defineStore('counter', () => {
// 1. state
const count = ref(0)
// 2. action
const increment = () => {
count.value++
}
// 3. getters
const doubleCount = computed(() => count.value * 2)
// 4. 返回 state、action、getters
return {
count,
increment,
doubleCount
}
})
注:pinia中没有mutations
3. 使用
对仓库中的数据做解构后会失去响应式,使用 storeToRefs保持响应式
<script setup lang="ts">
import { storeToRefs } from 'pinia';
// 1. 导入创建仓库的函数
import { useCounterStore } from './stores/counter'
// 2. 创建仓库
const counterStore = useCounterStore()
// 对仓库中的数据解构
const { count, doubleCount } = storeToRefs(counterStore)
// 对仓库中的方法解构
const { increment } = counterStore
</script>
<template>
<div>pinia</div>
<div>
<div>double:{{ doubleCount }}</div>
<button @click="increment">计数器:{{ count }}</button>
</div>
</template>