Pinia
Pinna 是 Vue 的状态管理库,支持跨组件、页面共享状态。
使用
采用组合式 API 的写法
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, doubleCount, increment };
});
export default useCounterStore;
在组件中使用:
import useCounterStore from '@/stores/counter';
const counterStore = useCounterStore();
console.log(counterStore);
console.log(counterStore.count);
counterStore 的打印结果是 一个 Proxy 对象,包括 $dispose
、$id
、$onAction
、$patch
、$reset
、$subscribe
、$state
、_hotUpdate
、_isOptionsAPI
等属性和方法,还包括自己在 store 中定义的 count
、increment
。所以在访问变量时不能写成counterStore.state.count
采用选项式 API 的写法
import { defineStore } from 'pinia';
const useCounterStore = defineStore('counter2', {
state: () => ({ count: 1 }),
getters: {
doubleCount: state => state.count * 2
},
actions: {
increment() {
this.count++;
}
}
});
export default useCounterStore;