您现在的位置是:亿华云 > 系统运维
Vue新的状态管理库Pinia入门教程
亿华云2025-10-03 13:57:56【系统运维】2人已围观
简介前沿Vue官方推荐的状态管理库是Vuex,那为什么最近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/pinia1、安装npm install pinia -S2、理库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的门教入门教程就讲到这,是不是站群服务器语法更加简洁
很赞哦!(85197)