Pinia状态管理

Pinia与Vuex对比

什么是Pinia

  • 2019年,为Vue重新设计状态管理,让它用来像组合式API
  • 最初的设计原则依然相同,并且同时兼容Vue2、Vue3
  • 本质上依然是一个状态管理的库,用于跨组件、页面进行状态共享

Pinia图标

在这里插入图片描述

Pinia与Vuex的区别

  • 与Vuex相比,Pinia提供了一个更简单的API,具有更少的仪式,提供了组合式API风格的API
  • 与TypeScript一起使用时具有可靠的类型推断支持
  • 优势:1、比如Mutations不再存在;2、更友好的TypeScript支持; 3、不再有modules的嵌套结构;4、也不再有命名空间的概念不需要记住它们的复杂关系

创建Pinia的Store

认识Store

  1. 一个实体,持有为绑定到你组件树的状态和业务逻辑,即保存了全局的状态
  2. 始终存在,并每个都可以读取和写入的组件
  3. 可以在你的应用程序中定义任意数量的Store来管理你的状态

Pinia三个核心概念

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

定义一个Store

  • 我们知道Store是使用defineStore() 定义的
  • 并且它需要一个唯一名称,作为第一个参数传递
// 返回一个函数,该函数的命名有自己的规范
const useCounter = defineStore("counter", {
    state: () => ({
        count: 99, 
    })
})
  • 这个name,也称为id,是必要的,Pinia使用它来将Store连接到devtools
  • 返回的函数,统一使用useX作为命名方案,这是约定的规范

使用定义的Store

  • Store在它被使用之前是不会创建的,我们可以通过调用use函数来使用Store
<template>
    <div class="home">
        <h2>Home View</h2> 
        <hr>
        <h2>count: {{ counterStore.count }}</h2>
        <button @click="incrementCount">count+1</button>
    </div>
</template>

<script setup>
    import useCounter from '@/stores/counter';
    import { storeToRefs } from 'pinia';
    import { toRefs } from 'vue';
    const counterStore = useCounter() 
    // 原来的响应式的方式
    // const { count } = toRefs(counterStore) 
    // 现pinia的响应式的方式
    const { count } = storeToRefs(counterStore)
    function incrementCount() {
        counterStore.count++
    }
</script>
  • 以上代码需要注意的是:Store获取到后不能被解构时,会失去响应式;为了从Store中提取属性同时保持其响应式,需要使用storeToRefs()
const { count } = counterStore // 不是响应式的
// 原来的响应式的方式
// const { count } = toRefs(counterStore) 
// 现pinia的响应式的方式
const { count } = storeToRefs(counterStore)

Pinia核心概念State

  • state是store的核心部分,因为store是用来帮助我们管理状态的
  • 在pinia中,状态被定义为返回初始状态的函数
const useUser = defineStore('user', {
    state: () => ({
        name: 'why',
        age: 18,
        level: 100
    })
})

操作State(一)

读取和写入state

  • 默认情况下,您可以通过store实例访问状态来直接读取和写入状态
	const userStore = useUser()

    const { name, age, level } = storeToRefs(userStore)
    function changeState() {
        // 1、一个个修改状态
        // userStore.name = 'kobe'
        // userStore.age = 24
        // userStore.level = 200 
}

重置State

  • 可以通过调用store上的$reset() 方法将状态重置到其初始值
function resetState() {
        // 将原来的状态返回
        userStore.$reset() 
    }

操作State(二)

改变State

  • 除了直接用store.counter++修改store,还可以使用$patch方法
  • 它允许你使用部分“state”对象同时应用多个更改
// 2、一次性修改多个状态
// userStore.$patch({
//     name:'james', 
//     age:35
// })

替换State

  • 你可以通过将其$state属性设置为新对象来替换整个store的整个状态
// 替换state为新的对象
userStore.$state = {
    name:'curry', 
    level:200
}

Pinia核心概念Getters

认识和定义Getters

Getters相当于Store的计算属性

  • 它可以用defineStore()中的getters属性定义
  • getters中可以定义接受一个state作为参数的函数
getters: {
   // 1、基本使用,你要对state操作,必须传入state
   doubleCount(state) {
       return state.count * 2 // 这里也可以通过this来访问
   },
   doubleCount: (state) => state.counter * 2
}

访问Getters(一)

  • 访问当前store的Getters
const countStore = useCounter() 
console.log(countStore.doubleCount)
  • Getters中访问自己的其他Getters
  • 我们可以通过this来访问到当前store实例的所有其他属性
// 2、在一个getter引入另一个getter
doubleCountAddOne() {
    // this就是store实例
    return this.doubleCount + 1
},
  • 访问其他store中的Getters
// pinia拥有扁平化的特点,意味着每个东西都是独立的
import useUser from "./user";

// 返回一个函数,该函数的命名有自己的规范
const useCounter = defineStore("counter", {
    state: () => ({
        count: 99,
        friends: [
            { id: 111, name: 'why' },
            { id: 112, name: 'kobe' },
            { id: 113, name: 'james' }
        ]
    }),
    getters: {
        // 4、getters中用到了别的store中的数据
        showMessage(state) {
            // 1、先获取user信息
            const userStore = useUser()
            // 2、获取自己的信息
            // 3、拼接信息
            return `name:${userStore.name}-count:${state.count}`
        }
    }

访问Getters(二)

  • Getters也可以返回一个函数,这样就可以接受参数
// 3、getters也支持返回一个函数
getFriendById(state) {
    // 别人在用这个的时候,实际上拿到的是一个函数
    return function (id) {
        // 使用普通函数来进行查找
        for (let i = 0; i < state.friends.length; i++) {
            const friend = state.friends[i]
            if (friend.id === id) {
                return friend
            }
        }
    }
},

// 在别的组件中使用的时候,可以直接传入参数
<template>
    <div class="home">
        <h2>Home View</h2>
        <hr>
        <h3>friend-111 {{ countStore.getFriendById(111) }}</h3>
    </div>
</template>

<script setup>
    import useCounter from '@/stores/counter';
    const countStore = useCounter() 
    console.log(countStore.doubleCount)
</script>

Pinia核心概念Actions

认识和定义Actions

Actions相当于组件中的methods

  • 可以使用defineStore() 中的actions属性定义,并且它们非常适合定义业务逻辑(通常是一些网络请求的业务逻辑)
  • 和getters一样,在actions中可以通过this访问整个store实例的所有操作
// counter.js
actions:{
        increment(num) {
            // console.log(state) // undefined
            this.count += num
        }
    }
 // home.js
 actions:{
        async fetchHomeMultidata() {
            const res = await fetch("http://123.207.32.32:8000/home/multidata")
            const data = await res.json() 
            // console.log(data)
            this.banners = data.data.banner.list
            this.recommends = data.data.recommend.list
            // 类似于return undefined
            // return Promise.resolve(undefined)

            // 也可以
            // return new Promise(async(resolve, reject))
        }
    }
  // 在别的组件中使用
// axios中的业务逻辑一般指的是网络请求等
const homeStore = useHome()
// homeStore.fetchHomeMultidata()
// 通过homeStore可以获取到异步数据
homeStore.fetchHomeMultidata().then(
    console.log('请求已经完成')
)

Github代码演练🔗

pinia练习

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值