位置:- 正文

【Vue全家桶】Pinia状态管理(vue全家桶学多久能上手项目)

编辑:rootadmin
【Vue全家桶】Pinia状态管理 【Vue全家桶】Pinia状态管理文章目录【Vue全家桶】Pinia状态管理写在前面一、认识Pinia1.1 认识Pinia1.2 为什么使用Pinia?二、 Store2.1 定义Store2.2 Option对象2.3 setup函数2.4 使用定义的Store三、Pinia核心概念State3.1 定义State3.2 操作State3.3 使用选项式 API 的用法四、Pinia核心概念Getters4.1 认识Getters4.2 访问Getters4.3 向Getters传递参数五、Pinia核心概念Actions5.1 认识Actions5.2 Actions执行异步操作5.3 访问其他 store 的 Actions写在前面

推荐整理分享【Vue全家桶】Pinia状态管理(vue全家桶学多久能上手项目),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vuex全家桶,vue全家桶学多久能上手项目,vue全家桶怎么用,vue全家桶学多久能上手项目,vuex全家桶,vue全家桶插件有哪些,vue2.0全家桶,vuex全家桶,内容如对您有帮助,希望把文章链接给更多的朋友!

🤗这里是前端程序员小张!

🌻人海茫茫,感谢这一秒你看到这里。希望我的文章对你的有所帮助!

🌟愿你在未来的日子,保持热爱,奔赴山海!

一、认识Pinia1.1 认识PiniaPinia开始于大概2019年,其目的是设计一个拥有 组合式 API 的 Vue 状态管理库目前同时兼容Vue2、Vue3,也并不要求你使用Composition APIPinia本质上依然是一个状态管理库,用于跨组件、页面进行状态共享

状态管理库是什么?

是一个保存状态和业务逻辑的实体,它会持有为绑定到你组件树的状态和业务逻辑,也就是保存了全局的状态;它有点像一个永远存在的组件,每个组件都可以读取和写入它;你可以在你的应用程序中定义任意数量的Store来管理你的状态;

应该在什么时候使用 Store?

一个 Store 应该包含可以在整个应用中访问的数据。这包括在许多地方使用的数据,例如显示在导航栏中的用户信息,以及需要通过页面保存的数据,例如一个非常复杂的多步骤表单。另一方面,应该避免在 Store 中引入那些原本可以在组件中保存的本地数据,例如,一个元素在页面中的可见性。

安装:npm install pinia

1.2 为什么使用Pinia?

使用 Pinia,即使在小型单页应用中,你也可以获得如下功能:

Devtools 支持追踪 actions、mutations 的时间线在组件中展示它们所用到的 Store让调试更容易的 Time travel热更新不必重载页面即可修改 Store开发时可保持当前的 State插件:可通过插件扩展 Pinia 功能为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。支持服务端渲染二、 Store

Store有三个核心概念:

state、getters、actions;等同于组件的data、computed、methods;一旦 store 被实例化,你就可以直接在 store 上访问 state、getters 和 actions 中定义的任何属性;2.1 定义Store

Store 是用 defineStore() 定义的

它需要一个唯一名称,作为第一个参数传递这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools。返回的函数统一使用useX作为命名方案,这是约定的规范defineStore() 的第二个参数可接受两类值:Setup 函数或 Option 对象import { defineStore } from 'pinia'// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。// 第一个参数是你的应用中 Store 的唯一 ID。export const useCounterStore = defineStore('counter', { // 其他配置...})2.2 Option对象

我们也可以传入一个带有 state、actions 与 getters 属性的 Option 对象:

我们可以认为state 是 store 的数据 (data)getters 是 store 的计算属性 (computed)而 actions 则是方法 (methods)export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ }, },})2.3 setup函数

与 Vue 组合式 API 的 setup 函数 相似

我们可以传入一个函数,该函数定义了一些响应式属性和方法并且返回一个带有我们想暴露出去的属性和方法的对象在 Setup Store 中:ref() 就是 state 属性computed() 就是 gettersfunction() 就是 actionsexport const useCounterStore = defineStore('counter', () => { const count = ref(0) function increment() { count.value++ } return { count, increment }})2.4 使用定义的Store【Vue全家桶】Pinia状态管理(vue全家桶学多久能上手项目)

Store在它被使用之前是不会创建的,我们可以通过调用**useStore()**来使用Store:

<script setup>import { useCounterStore } from '@/stores/counter'const store = useCounterStore()</script>一旦 store 被实例化,你可以直接访问在 store 的 state、getters 和 actions 中定义的任何属性。注意Store获取到后不能被解构,那么会失去响应式:为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()。三、Pinia核心概念State3.1 定义State

state 是 store 的核心部分,因为store是用来帮助我们管理状态的

在 Pinia 中,状态被定义为返回初始状态的函数import { defineStore } from 'pinia'export const useCounter = defineStore('counter', { // 为了完整类型推理,推荐使用箭头函数 state: () => { return { // 所有这些属性都将自动推断出它们的类型 counter: 0 } }})3.2 操作State

读取和写入State:

默认情况下,您可以通过 store 实例访问状态来直接读取和写入状态const counterStore = useCounter()counterStore.counter++

重置State

你可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值const counterStore = useCounter()counterStore.$reset()

变更State

除了用 store.count++ 直接改变 store,你还可以调用 $patch 方法它允许你用一个 state 的对象在同一时间更改多个属性counterStore.$patch({ counter : 1, age: 120, name: 'pack',})3.3 使用选项式 API 的用法// 示例文件路径:// ./src/stores/counter.jsimport { defineStore } from 'pinia'const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }),})四、Pinia核心概念Getters4.1 认识Getters

Getters 完全等同于 store 的 state 的计算属性

可以通过 defineStore() 中的 getters 属性来定义它们。推荐使用箭头函数,并且它将接收 state 作为第一个参数export const useCounter = defineStore('counter', { state: () => ({ counter: 15 }), getters: { doubleCounter: (state) => state.counter * 2 }})4.2 访问Getters

访问当前store 实例上的 getters

const counterStore = useCounter()console.log(counterStore.doubleCounter)

Getters中访问当前store实例的其他Getters

我们可以通过 this,你可以访问到其他任何 gettersgetters: { doubleCount: (state) => state.counter * 2, // 返回 counter 的值乘以 2 加 1 doubleCountPlusOne() { return this.doubleCount + 1 }}

访问其他store实例的Getters

getters: { otherGetter(state) { const otherStore = useOtherStore() return state.localData + otherStore.data }}4.3 向Getters传递参数

Getters可以 返回一个函数,该函数可以接受任意参数:

export const useUserListStore = defineStore('main', { state: () => ({ users: [ { id: 1, name: 'lisa' }, { id: 2, name: 'pack' } ] }), getters: { getUserById: (state) => { return (userId) => { state.users.find((user) => user.id === userId) } } }})

在组件中使用:

<template> <p>User 2: {{ getUserById(2) }}</p></template><script setup>import { useUserListStore } from './store'const userList = useUserListStore()const { getUserById } = storeToRefs(userList)</script>五、Pinia核心概念Actions5.1 认识Actions

Actions 相当于组件中的 methods。

可以通过 defineStore() 中的 actions 属性来定义,并且它们也是定义业务逻辑的完美选择。

类似 Getters,Actions 也可通过 this 访问整个 store 实例

export const useCounterStore = defineStore('counter', { state: () => ({ counter: 15 }), actions: { increment() { this.counter++ } }})5.2 Actions执行异步操作

Actions 中是支持异步操作的,并且我们可以编写异步函数,在函数中使用await:

actions: { increment() { this.counter++ }, async fetchDataAction() { const res = await fetch("http://jsonplaceholder.typicode.com/posts") const data = await res.json() return data }}

Actions 可以像函数或者通常意义上的方法一样被调用:

<script setup>import { useCounterStore } from './store/couter';const counterStore = useCounterStore()counterStore.fetchDataAction().then(res => { console.log(res)})</script>5.3 访问其他 store 的 Actionsimport { useAuthStore } from './auth-store'export const useSettingsStore = defineStore('settings', { state: () => ({ preferences: null, // ... }), actions: { async fetchUserPreferences() { const auth = useAuthStore() if (auth.isAuthenticated) { this.preferences = await fetchPreferences() } else { throw new Error('User must be authenticated') } }, },})
本文链接地址:https://www.jiuchutong.com/zhishi/300793.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/300794.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络