vue3 pinia详解
文章目录
pinia与vuex类似,是一种新的状态管理工具。
1. pinia 的特点(相比于 vuex)
① 更加支持TS
② 更加轻量
③ 去除了 mutations 与 modules 相关概念,只有 state、getters、actions
④ action 可以同时支持同步和异步操作
⑤ 同时支持 vue2 和 vue3
2. pinia 的使用
① 安装并注册 pinia
npm i pinia
// main.ts
import { createPinia } from "pinia"
const pinia = createPinia()
app.use(pinia)
② 使用 defineStore 方法创建一个基于 pinia 的 store 仓库,每一个模块可以单独创建一个 store 仓库(类似于 hook),例如:用户相关的 pinia 仓库—— useUserStore.ts
// useUserStore.ts
import { defineStore } from "pinia"
// 第一个参数为当前store 的 id,即唯一标识
export const useUserStore = defineStore("store", {
// state 必须是一个回调函数
state: () => {
return {
userName: "testName",
age: 22
}
},
// getters 对象,类似于 computed
getters: {
getName():string {
return `getter-${this.userName}`
}
},
// actions 对象,类似于 methods,同步和异步都可以
actions: {
setAge() {
// 使用this可以获取到state,所以不能使用箭头函数!
this.age++
}
}
})
③ 在组件中使用:
// test.vue
<script setup lang="ts">
import { ref, reactive } from 'vu