1. 定义Store【src\stores\counter.ts】。
(1). 组合式API写法。
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
(2). 类似Vuex的写法。
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state:()=>({count:0}), // 相当于 state:()=>{ return {count:0}; }。
getters:{
doubleCount:state=>state.count * 2,
},
actions:{
increment(){
this.count++;
}
}
})
2. 使用Store【src\views\ChildComponent.vue】。
(1). 组合式API写法。
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore();
function reset(){
// 三种改变state的方法展示。
counter.count=0; // 直接变更。
// counter.$patch(state=>{state.count=0}) // 传入箭头函数来变更。
// counter.$patch({count:0}) // 传入新的state对象来变更。
}
</script>
<template>
<div>
<div @click="counter.increment()">{{ counter.count }}、{{ counter.doubleCount }}</div>
<button @click="reset()">reset</button>
</div>
</template>
(2). 组合式API写法 中 使用解构语法。
<script setup>
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore();
let { count,doubleCount } = storeToRefs(counter);
const { increment } = counter;
function reset(){
// 四种改变state的方法展示。
count.value = 0; // 需要通过.value来改变响应式ref的值,这样写能够直接改变counter中state count的值。
// counter.count=0;
// counter.$patch(state=>{state.count=0}) // 传入箭头函数来变更。
// counter.$patch({count:0}) // 传入新的state对象来变更。
}
</script>
<template>
<div>
<div @click="increment()">{{ count }}、{{ doubleCount }}</div>
<button @click="reset()">reset</button>
</div>
</template>
(3). 选项式API写法。
<script>
import {mapState,mapActions,mapStores} from 'pinia'; // mapGetters,
import {useCounterStore} from '@/stores/counter';
export default{
computed:{
...mapStores(useCounterStore), // 如果还有其它Stores要引入,那么就在useCounterStore后面加上“,其它Stores”。
...mapState(useCounterStore,['count','doubleCount']), // mapState现在返回的接口 已经 包含getters了。
// ...mapGetters(useCounterStore,['doubleCount']), // 已经不推荐使用mapGetters了。
},
methods:{
...mapActions(useCounterStore,['increment']),
reset(){
this.counterStore.count = 0;
// this.counterStore.$patch({count:0});
// this.counterStore.$patch(state=>{state.count=0});
}
}
}
</script>
<template>
<div>
<div @click="increment()">{{ count }}、{{ doubleCount }}</div>
<button @click="reset()">reset</button>
</div>
</template>