Vue新的状态管理库Pinia入门教程

前沿

Vue官方推荐的状态管理库是Vuex,那为什么最近Pinia会火起来呢,主要在于Vue3推出来的时候,Vuex对于Vue3的组合式Api支持的不是特别好,也就是在这个时候Pinia出现了,最重要的是,Pinia不但支持Vue3,同时还支持Vue2,这就厉害了,而且最新Vuex5的特性还是参考的Pinia

使用教程

官网:https://pinia.vuejs.org/

github地址:https://github.com/vuejs/pinia

1、安装

npm install pinia -S

2、vue中引入

// Vue3中引入使用
import { createPinia } from 'pinia'

app.use(createPinia())


//Vue2中引入使用
import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
el: '#app',
// 其它配置项
pinia,
})

3、基本使用

// 定义store
// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
// 状态值定义
state: () => {
return { count: 0 }
},
// 状态更改方法定义
actions: {
increment() {
this.count++
},
},
})

// 在组件中使用
// 导入状态
import { useCounterStore } from '@/stores/counter'

export default {
setup() {
// 初始化一个store实例
const counter = useCounterStore()

// state更新
counter.count++

// 或者调用方法更新
counter.increment()
},
}

4、也可以像vuex一样使用

const useCounterStore = defineStore('counter', {
// 状态值
state: () => ({ count: 0 }),
// getter值
getters: {
double: (state) => state.count * 2,
},
// actions方法
// 注意pinia里没有mutation
actions: {
increment() {
this.count++
}
}
})

// 定义另外一个store
const useUserStore = defineStore('user', {
// ...
})

export default {
// computed里引入使用state里的值
computed: {
...mapStores(useCounterStore, useUserStore)
...mapState(useCounterStore, ['count', 'double']),
},
// methods里使用action
methods: {
...mapActions(useCounterStore, ['increment']),
},
}

好了,Pinia的入门教程就讲到这,是不是语法更加简洁

THE END