小程序开发|小程序制作|小程序开发网

搜索

vue3新一代状态管理库 Pinia

2023-3-15 22:16| 发布者: EW88888| 查看: 464| 评论: 0

摘要: Pinia优势Pinia是一个全新的Vue状态管理库,是Vuex的代替者,尤雨溪强势推荐1.Vue2 和 Vue3 都能支持2.抛弃传统的 Mutation ,只有 state, getter 和 action ,简化状态管理库3.不需要嵌套模块,符合 Vue3 的 Compos

Pinia优势

Pinia是一个全新的Vue状态管理库,是Vuex的代替者,尤雨溪强势推荐

1.Vue2 和 Vue3 都能支持
2.抛弃传统的 Mutation ,只有 state, getter 和 action ,简化状态管理库
3.不需要嵌套模块,符合 Vue3 的 Composition api,让代码扁平化
4.TypeScript支持

Pinia 基本使用

初始化项目: npm init vite@latest
安装Pinia: npm i pinia

挂载Pinia

import { createPinia } from 'pinia'const pinia = createPinia()createApp(App).use(pinia)

创建Store

import { defineStore } from "pinia";export const useStore = defineStore('main', {  state: () => {    return {      msg: 'hello world hhhh',      Number: 1    }  },  getters: {},  actions: {}})

使用Store

解构Store

当store中的多个参数需要被使用到的时候,为了更简洁的使用这些变量,我们通常采用结构的方式一次性获取所有的变量名

ES传统方式解构(能获取到值,但是不具有响应性)
Pinia解构方法:storeToRefs

多条数据修改

通过基础数据修改方式去修改多条数据也是可行的,但是在 pinia 官网中,已经明确表示$patch 的方式是经过优化的,会加快修改速度,对性能有很大好处,所以在进行多条数据修改的时候,更推荐使用$patch

$patch 方法可以接受两个类型的参数,函数 和 对象
$patch + 对象
$patch + 函数: 通过函数方式去使用的时候,函数接受一个 state 的参数,state 就是 store 仓库中的 state
const change = () => {  store.$patch({    msg: 'hhhhhhhhhhhh',    number: store.number + 100  })}const change1 = () => {  store.$patch((state)=> {    state.msg = 'hhhhhhhhhhhh'    state.number = state.number + 100  })}
Pinia中的Getters

Pinia 中的 getter 和 Vue 中的计算属性几乎一样,在获取 State值之前做一些逻辑处理getter 中的值有缓存特性,如果值没有改变,多次使用也只会调用一次添加 getter方法

getters: {    addNumber(state) {      return state.number * state.number1    }  },
{{store.addNumber}}
{{store.addNumber}}
{{store.addNumber}}
//多次调用也只会执行一次

getter 中不仅可以传递 state 直接改变数据状态,还可以使用 this 来改变数据,但要说明对应类型

getters: {    addNumber():any {      // return state.number * state.number1      return this.msg    }  },
store之间的相互调用

在 Pinia 中,可以在一个 store 中 import 另外一个 store ,然后通过调用引入 store 方法的形式,获取引入 store 的状态

export const useStore = defineStore('use', {  state: () => {    return {      msg: 'hello world hhhhxxx',      number: 2,      number1: 3    }  },  getters: {    addNumber():any {      // return state.number * state.number1      return this.msg    }  },  actions: {  }})export const mainStore = defineStore('main', {  state: () => {    return {      msg: 'hello world hhhh',      number: 1    }  },  getters: {    addNumber() {      console.log(useStore().msg);    }  },  actions: {}})

总结

总得来说,Pinia 就是 Vuex 的替代版,可以更好的兼容 Vue2,Vue3以及TypeScript。在Vuex的基础上去掉了 Mutation,只保留了 state, getter和action。Pinia拥有更简洁的语法, 扁平化的代码编排,符合Vue3 的 Composition api


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部