vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Pinia状态管理

Vue之Pinia状态管理

作者:前端程序员小张

这篇文章主要介绍了Vue中Pinia状态管理,Pinia开始于大概2019年,其目的是设计一个拥有 组合式 API 的 Vue 状态管理库,Pinia本质上依然是一个状态管理库,用于跨组件、页面进行状态共享,感兴趣的同学可以参考阅读

一、认识Pinia

1.1 认识Pinia

状态管理库是什么?

应该在什么时候使用 Store?

安装:npm install pinia

1.2 为什么使用Pinia?

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

二、 Store

Store有三个核心概念:

2.1 定义Store

Store 是用 defineStore() 定义的

import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useCounterStore = defineStore('counter', {
  // 其他配置...
})

2.2 Option对象

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

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

2.3 setup函数

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

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

2.4 使用定义的Store

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

<script setup>
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
</script>

三、Pinia核心概念State

3.1 定义State

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

import { defineStore } from 'pinia'

export const useCounter = defineStore('counter', {
  // 为了完整类型推理,推荐使用箭头函数
  state: () => {
    return {
      // 所有这些属性都将自动推断出它们的类型
      counter: 0
    }
  }
})

3.2 操作State

读取和写入State

const counterStore = useCounter()
counterStore.$reset()

重置State

const counterStore = useCounter()
counterStore.$reset()

变更State

counterStore.$patch({
  counter : 1,
  age: 120,
  name: 'pack',
})

3.3 使用选项式 API 的用法

// 示例文件路径:
// ./src/stores/counter.js

import { defineStore } from 'pinia'

const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
})

四、Pinia核心概念Getters

4.1 认识Getters

Getters 完全等同于 store 的 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

getters: {
  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核心概念Actions

5.1 认识Actions

Actions 相当于组件中的 methods。

export const useCounterStore = defineStore('counter', {
  state: () => ({
    counter: 15
  }),
  actions: {
    increment() {
      this.counter++
    }
  }
})

5.2 Actions执行异步操作

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

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

5.3 访问其他 store 的 Actions

import { 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')
      }
    },
  },
})

以上就是Vue之Pinia状态管理的详细内容,更多关于Pinia状态管理的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文