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

开发 项目管理
为什么最近Pinia会火起来呢,主要在于Vue3推出来的时候,Vuex对于Vue3的组合式Api支持的不是特别好,也就是在这个时候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的入门教程就讲到这,是不是语法更加简洁

责任编辑:姜华 来源: 今日头条
相关推荐

2022-05-23 08:59:02

piniavue插件

2021-12-16 08:47:56

Vue3 插件Vue应用

2011-07-04 11:38:06

MySQL

2022-02-18 09:39:51

Vue3.0Vue2.0Script Set

2022-10-09 09:18:01

ColadaPinia

2021-07-16 22:49:50

PiniaVuex替代品

2009-07-08 15:12:48

Java Servle

2014-05-26 15:35:55

Web组件Web Compone

2010-08-03 13:06:15

Flex Builde

2013-08-29 14:12:52

Storm分布式实时计算

2010-03-12 14:04:32

Python入门教程

2022-07-12 08:27:18

Zadig开源

2022-07-21 11:58:12

Docker

2018-07-05 11:30:56

数据库浏览器IndexedDB

2022-01-18 20:27:32

Pinia.jsVue.jsVue

2009-06-15 13:59:00

netbeans6.1入门教程

2018-03-22 14:59:13

Docker入门容器

2010-06-18 16:56:50

UML建模语言

2011-09-02 10:59:10

jQuery Mobi

2010-07-20 16:19:54

Perl
点赞
收藏

51CTO技术栈公众号