pinia优点
- 完整的TypeScript支持
- 极其轻巧(体积1k)
- store的action被调度为常规的函数调用,而不是使用dispatch方法或mapAction辅助函数
- 支持多个store
- 支持vue devtools、ssr、webpack代码拆分
pinia缺点
- 不支持调试功能,如时间旅行和编辑
大致总结:
- 支持选项式api和组合式api
- pinia没有mutations,只有state、getters、actions
- pinia分模块不需要modules(vuex分模块是需要modules)
- TypeScript支持很好
- 自动化代码拆分
- pinia体积更小(性能更好)
pinia使用介绍
// store
import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
state: () => {
return {
num: 0,
name: 'shenlong'
}
},
getters: {
changeNum() {
return this.num + 1000
}
},
actions: {
upNum(val) {
this.num += val
}
}
})
// xxx.vue
<template>
<div>
<div>{{ name }}</div>
<div>{{ num }}</div>
<div>{{ changeNum }}</div>
<button @click="fn">dianwo</button>
<button @click="btn">actions</button>
</div>
</template>
<script setup>
import { storeToRefs } from "_pinia@2.0.27@pinia";
import { useStore } from "../../store/index";
let store = useStore();
console.log(store);
let { name, num, changeNum } = storeToRefs(store);// 解构时可以使用storeToRefs保持其响应式
const fn = () => {
// console.log(name);
// name.value='23'
// $patch允许你用一个 `state` 的补丁对象在同一时间更改多个属性:
store.$patch({
num: 123456,
name: "123456",
});
};
const btn = () => {
store.upNum(1);
};
</script>