前言
伴随vue2到vue3的升级,官方已经用Pinia代替了Vuex成为官方的状态管理库。
一、Pinia是什么及特点?
1、Pinia是什么
在 vue 2.x 中,vuex 是官方的状态管理库,vue3官方强势推荐使用 pinia 作为状态管理库。
2、Pinia的特点
1、Pinia支持 vue2 和 vue3;
2、支持 vue3 中 setup 的写法,可以按照 setupComposition API 的方式返回状态和改变状态的方法,实现代码的扁平化;
3、支持 vuex 中 state、actions、getters 形式的写法,不再使用 mutations,开发时候不用根据同步异步来决定使用 mutations 或 actions,pinia 中只有 actions;
4、对 TypeScript 支持非常友好。
二、使用步骤
1.安装库
代码如下(示例):
yarn add pinia
# 或者使用 npm
npm install pinia
2.创建Pinia
1.1 main.ts文件
import { createApp } from 'vue'
import App from './App.vue'
import {setupStore} from './store/index'
const app = createApp(App)
setupStore(app)
app.mount('#app')
1.2 创建store文件夹下的index.ts
import type { App } from 'vue'
import { createPinia } from 'pinia'
const store = createPinia()
export const setupStore = (app: App<Element>) => {
app.use(store)
}
export { store }
1.3 创建store文件夹下modules的文件夹,创建useAppStore.ts
import { defineStore } from 'pinia'
interface AppState{
count: number,
list: Array<number>,
name: string,
age: number
}
export const useAppStore = defineStore('app', {
state: ():AppState => {
return {
count: 0,
list: [],
name: '',
age: 0
}
},
actions: {
addCount(step:number) {
this.count+=step
}
},
getters: {
doubleCount(state) {
return state.count*2
}
}
})
1.4 组件使用Pinia
<script setup lang="ts">
import { useAppStore } from './store/modules/useAppStore'
import { storeToRefs } from 'pinia'
const store = useAppStore()
// 转化响应式对象
const { count,doubleCount,list,name,age } = storeToRefs(store)
const { addCount } = store
const changeInfo = ()=>{
//批量更新
store.$patch(state=>{
state.count++;
state.list.push(1);
state.name = 'qwe';
state.age = 20
})
}
</script>
<template>
<div>
<button @click="addCount(10)">+1</button>
<button @click="changeInfo">批量更新</button>
<h2>count:{{count}}</h2>
<h2>{{list}}</h2>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>doubleCount:{{doubleCount}}</h2>
</div>
</template>
<style scoped>
</style>
总结
以上仅仅简单介绍了Pinia在Vue3+Typescript中的使用,Pinia对于typescript的支持性更好,同时也简化了很多方法的写法。