文章目录
1. Pinia 与 Vuex 的区别
- Pinia 是 Vue 的状态管理库,相当于 Vuex 取消了 mutations,取消了 Module 模块化命名空间
- 现在的 pinia 采用的是扁平化,每一块 store 都是一个命名空间
- 还支持了 plugins 等
2. pinia 安装与搭建
- 使用 npm 安装
npm i pinia
- 创建
store/index.js
文件import { defineStore } from "pinia" // defineStore(当前 store 的 Id, {配置项}) export const useCountStore = defineStore("count", { // 状态 state: () => { return { count: 1 } }, // 计算属性 getters: { // 这里的计算属性使用时,为一个属性而不是方法 increaseNum(store) { return store.count * 10 } }, // 方法 actions: { addCount(value) { this.count += value } } })
- 在
main.js
中引入// 这是 Vue3 的引入方式,Vue2 不太一样 import { createApp } from "vue"; import App from "./App.vue"; import { createPinia } from "pinia"; const app = createApp(App); app.use(createPinia()); app.mount("#app");
这样就可以在任意位置引入 store 了
3. pinia 的使用
3.1 基本使用
<script setup>
import { useCountStore } from "../store/index.js";
// 可以直接通过 store. 去获取 state、getters、actions 中的属性和方法了
const countStore = useCountStore();
// 直接获取
countStore.count // 1
// 计算属性获取
countStore.increaseNum // 10
// 修改状态1
countStore.count += 1
// 修改状态2
countStore.addCount(1)
// 修改状态3,这种方式和 React 中的 setState 很像
countStore.$patch({
count: countStore.count + 1
})
// 修改状态4
countStore.$patch((state) => {
state.count += 1
})
// 替换状态(不是覆盖状态),需要新的状态去替换旧的,如果 key 值不相同就是添加新状态
countStore.$state = {count: 2}
// 重置状态
countStore.$reset()
// 这个时候在使用其他组件引入 countStore 时,count 也是为最新的
</script>
3.2 订阅状态
<script setup>
import { useCountStore } from "../store/index.js";
const countStore = useCountStore();
// store 中的值,每修改一次就会触发
countStore.$subscribe(({ events, storeId, type }, state) => {
// 里面包含了一些信息
events
// 这个 store 的 Id,这里是 count
storeId
/*
修改值的方式:
'direct':直接修改、使用 action 中的方式修改
'patch object':使用 $patch({}) 修改
'patch function':使用 $patch((state)=>{}) 修改、使用 $state 替换、$reset()重置
*/
type
});
</script>
3.3 订阅 actions
<script setup>
import { useCountStore } from "../store/index.js";
const countStore= useCountStore();
// action 中的函数每次调用,都会触发一次
countStore.$onAction(({ args, name, store, after, onError }) => {
// 调用 actions 中函数的传参列表
args
// 函数名称
name
// store 对象
store
// 当函数正常执行完成后执行
// result 接收函数返回成功状态的 Promise
after((result) => {
console.log(result);
});
// 当函数中存在失败状态的 Promise,或函数抛出异常时执行
onError((err) => {
console.log(err);
});
});
</script>
4. 定义 Store
4.1 Option Store
// 这里相当于 vue2 的选项式 API
export const useCountStore = defineStore('count', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
4.2 Setup Store
// 这里相当于 vue3 的组合式 API
export const useCountStore = defineStore('count', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})