Pinia状态管理工具:【Vue3 + Pinia使用】 安装Pinia && Pinia基本使用 && 创建 store仓库 && Pinia持久化存储 && 配置本地存储 && 指定仓库数据存储

LiuJInTao: 2024年4月13日00:24

Pinia状态管理工具

一、Pinia

1. 什么是 Pinia

Pinia官网:Pinia
在这里插入图片描述

2. 手动添加 Pinia

在这里插入图片描述
安装
用你喜欢的包管理器安装 pinia:

yarn add pinia
或者使用 npm
npm install pinia

TIP

如果你的应用使用的 Vue 版本低于 2.7,你还需要安装组合式 API 包:@vue/composition-api。如果你使用的是 Nuxt,你应该参考这篇指南。

如果你正在使用 Vue CLI,你可以试试这个非官方插件。

创建一个 pinia 实例 (根 store) 并将其传递给应用:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

如果你使用的是 Vue 2,你还需要安装一个插件,并在应用的根部注入创建的 pinia:

import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // 其他配置...
  // ...
  // 请注意,同一个`pinia'实例
  // 可以在同一个页面的多个 Vue 应用中使用。 
  pinia,
})

这样才能提供 devtools 的支持。在 Vue 3 中,一些功能仍然不被支持,如 time traveling 和编辑,这是因为 vue-devtools 还没有相关的 API,但 devtools 也有很多针对 Vue 3 的专属功能,而且就开发者的体验来说,Vue 3 整体上要好得多。在 Vue 2 中,Pinia 使用的是 Vuex 的现有接口 (因此不能与 Vuex 一起使用) 。

3. Pinia 的基本使用

在这里插入图片描述

1. 创建仓库store
// Pinia 仓库
/**
 * 定义 store仓库语法:
 *          - defineStore(仓库的名称, () => {数据逻辑....})
 * 
 */

import { defineStore } from 'pinia'
import { ref, computed} from 'vue'

export const userCounterStore = defineStore('counter', () => {
    // 声明仓库数据
    const count = ref(100)

    // 仓库处理函数actions(就相当于普通函数)
    const handleAdd = () => count.value++
    const handleSub = () => count.value--

    // 计算属性
    const number = computed(() => count.value * 2)

    // 声明仓库数据
    const message = ref('Pinia 仓库')




    // return 仓库数据,外部调用
    return {
        count,
        handleAdd,
        handleSub,
        number,
        message,
    }
})
2. 组件中使用
<script setup>
  import Son1Com from "./components/Son1Com.vue";
  import Son2Com from "./components/Son2Com.vue";

  // 导入仓库暴露出来的对象引用
  import { userCounterStore } from '@/store/counter'

  const counterStore = userCounterStore()

  // const count = ref(0)
</script>

<template>
  <div>
    <h3>我是 APP 根组件 - {{ counterStore.count }} </h3> <span>{{ counterStore.message }}</span>
    
    <Son1Com></Son1Com>
    <Son2Com></Son2Com>
  </div>
</template>

<style scoped>

</style>





console.log('--------------------------------------')
<script setup>
  // 导入仓库方法
 import { userCounterStore } from '@/store/counter' 
  // 通过方法创建对象
 const counterStore = userCounterStore()
</script>
<template>
    <div>
        <div>我是 Son1Com - {{ counterStore.count }} --- {{ counterStore.number }}</div>
        <button @click="counterStore.handleAdd">+</button>
    </div>

</template>

<style scoped>

</style>
    


console.log('--------------------------------------')


<script setup>
    // 1. 导入仓库方法
    import { userCounterStore } from '@/store/counter'
    // 2. 使用方法创建对象
    const counterStore = userCounterStore()

</script>
<template>
    <div>我是 Son2Com - {{ counterStore.count }}</div>
    <button @click="counterStore.handleSub">-</button>
</template>

<style scoped>

</style>
    



这样就能够实现数据同步共享了。

4. action 异步实现

在这里插入图片描述

  • 在项目中安装一下 axios 库
yarn add axios
  • 创建仓库进行代码编写
import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useChannelStore = defineStore( 'channel', () => {
    // 仓库数据
    const channelList = ref([])

    // action 操作数据的方法 (支持异步)
    const getList = async () => {
        const {data: { data }} = await axios.get('http://geek.itheima.net/v1_0/channels')
        channelList.value = data.channels
        console.log(data.channels)
    }

    // getters

    return {
        channelList,
        getList
    }
})
5. store 解构的响应式问题

在这里插入图片描述

  • 我们通过实例调用数据也行。当我们数据太多了,就可以使用解构的方法进行处理数据。但是需要注意响应式的问题。(方法可以直接解构,因为我们只是调用方法,没有其他修改等操作)。
6. Pinia 持久化存储

【官网地址】: Pinia插件官网
在这里插入图片描述
快速开始

  • 概述
    本插件兼容 pinia^2.0.0,在使用之前请确保你已经 安装 Pinia。 pinia-plugin-persistedstate 丰富的功能可以使 Pinia Store 的持久化更易配置:

与 vuex-persistedstate 相似的 API
所有 Store 均可单独配置
自定义 storage 和数据序列化
恢复持久化数据前后的 hook
每个 Store 具有丰富的配置
兼容 Vue 2 和 3
无任何外部依赖

  • 安装
    包管理器安装依赖:

npm

npm i pinia-plugin-persistedstate

将插件添加到 pinia 实例上

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

用法
创建 Store 时,将 persist 选项设置为 true。

选项式语法

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => {
    return {
      someState: '你好 pinia',
    }
  },
  persist: true,
})

组合式语法

import { defineStore } from 'pinia'

export const useStore = defineStore(
  'main',
  () => {
    const someState = ref('你好 pinia')
    return { someState }
  },
  {
    persist: true,
  },
)

现在,你的整个 Store 将使用默认持久化配置保存。
在这里插入图片描述

  • 将上面创建的两个仓库进行持久化,我们本地就能进行存储数据了。
7. 配置 本地存储的 key 名字

配置
该插件的默认配置如下:

使用 localStorage 进行存储
store.$id 作为 storage 默认的 key
使用 JSON.stringify/JSON.parse 进行序列化/反序列化
整个 state 默认将被持久化
如何你不想使用默认的配置,那么你可以将一个对象传递给 Store 的 persist 属性来配置持久化。

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {
  state: () => ({
    someState: '你好 pinia',
  }),
  persist: {
    // 在这里进行自定义配置
  },
})

key
类型:string
默认值:store.$id
Key 用于引用 storage 中的数据

例如

import { defineStore } from 'pinia'

export const useStore = defineStore('store', {
  state: () => ({
    someState: '你好 pinia',
  }),
  persist: {
    key: 'my-custom-key',
  },
})

这个 Store 将被持久化存储在 localStorage 中的 my-custom-key key 中。

8. 指定仓库中某些数据进行持久化

paths

类型:string[]
默认值:undefined
用于指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态,undefined 或 null 表示持久化整个 state。

例如

import { defineStore } from 'pinia'

export const useStore = defineStore('store', {
  state: () => ({
    save: {
      me: 'saved',
      notMe: 'not-saved',
    },
    saveMeToo: 'saved',
  }),
  persist: {
    paths: ['save.me', 'saveMeToo'],
  },
})

该 store 中, 只有 save.me 和 saveMeToo 被持久化,而 save.notMe 不会被持久化。

  • Pinia 的使用:总而言之,参考官网文档进行使用配置即可。

二、Pinia 总结

在这里插入图片描述

  • 21
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

脱发使我稳重

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值