Pinia安装使用和持久化和模块化

一、什么是Pinia

image.png

二、手动添加Pinia到Vue项目

官网:Pinia | Pinia (vuejs.org)

2.1. 安装

用你喜欢的包管理器安装 pinia

npm install pinia
# or with yarn 
yarn add pinia

2.2. 在入口文件main.js中注册Pinia

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')

三、Pinia的使用

文件目录如下
在这里插入图片描述

3.1. 定义 Store

在深入研究核心概念之前,我们得知道 Store 是用 defineStore() 定义的,它的第一个参数要求是一个独一无二的名字:

import { defineStore } from 'pinia'

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

这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools。为了养成习惯性的用法,将返回的函数命名为 use… 是一个符合组合式函数风格的约定。

3.1.1 Option Store

与 Vue 的选项式 API 类似,我们也可以传入一个带有 state、actions 与 getters 属性的 Option 对象

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

你可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。

3.1.2. Setup Store

也存在另一种定义 store 的可用语法。与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。

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

  return { count, increment }
})

Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions

Setup store 比 Option Store 带来了更多的灵活性,因为你可以在一个 store 内创建侦听器,并自由地使用任何组合式函数。不过,请记住,使用组合式函数会让 SSR 变得更加复杂。

3.1.3. 你应该选用哪种语法?

在 Vue 中如何选择组合式 API 与选项式 API 一样,选择你觉得最舒服的那一个就好。如果你还不确定,可以先试试 Option Store

3.2. 使用 Store

虽然我们前面定义了一个 store,但在我们使用 <script setup> 调用 useStore()(或者使用 setup() 函数,像所有的组件那样) 之前,store 实例是不会被创建的:

<script setup>
import { useCounterStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量 ✨
const store = useCounterStore()
</script>

请注意,store 是一个用 reactive 包装的对象,这意味着不需要在 getters 后面写 .value,就像 setup 中的 props 一样,如果你写了,我们也不能解构它

<script setup>
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
// ❌ 这将不起作用,因为它破坏了响应性
// 这就和直接解构 `props` 一样
const { name, doubleCount } = store 
name // 将始终是 "Eduardo" 
doubleCount // 将始终是 0 
setTimeout(() => {
  store.increment()
}, 1000)
// ✅ 这样写是响应式的
// 💡 当然你也可以直接使用 `store.doubleCount`
const doubleValue = computed(() => store.doubleCount)
</script>

为了从 store 中提取属性时保持其响应性,你需要使用 storeToRefs()。它将为每一个响应式属性创建引用。当你只使用 store 的状态而不调用任何 action 时,它会非常有用。请注意,你可以直接从store 中解构 action,因为它们也被绑定到 store 上:

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>

四、Pinia数据持久化

官方文档: 快速开始 | pinia-plugin-persistedstate (prazdevs.github.io)

概述

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

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

4.1. 安装插件

npm i pinia-plugin-persistedstate
//或者
pnpm i pinia-plugin-persistedstate
//或者
yarn add pinia-plugin-persistedstate

4.2. 将插件添加到 pinia 实例上

// main.js
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

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

const app = createApp(App)

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

4.3. 使用

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

4.3.1. 选项式语法

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

4.3.2. 组合式语法

import { defineStore } from 'pinia'

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

    return { count, increment }
  },
  {
    persist: true
  }
)

现在,你的整个 Store 将使用默认持久化配置保存。

该插件的默认配置如下:

如何你不想使用默认的配置,那么你可以将一个对象传递给 Store 的 persist 属性来配置持久化。

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  },
  persist: {
    // 在这里进行自定义配置
  }
})

五、Pinia - 配置仓库统一管理

在这里插入图片描述

5.1. stores / modules / user.js

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('big-user', () => {
  const token = ref('')
  const setToken = (newToken) => {
    token.value = newToken
  }

  const removeToken = () => {
    token.value = ''
  }

  return {
    token,
    setToken,
    removeToken
  }
})

5.2. stores / modules / counter.js

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('big-counter', () => {
  const count = ref(100)
  const addCount = (count) => {
    count.value += count
  }

  return {
    count,
    addCount
  }
})

5.3. stores / index.js

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

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

export default pinia

// import { useUserStore } from '@/store/modules/user.js'
// export { useUserStore }
// import { useCounterStore } from '@/store/modules/counter.js'
// export { useCounterStore }

// 简写
export * from './modules/user'
export * from './modules/counter'

5.4. main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

import pinia from '@/store/index'

import '@/assets/main.scss'

const app = createApp(App)

app.use(pinia)
app.use(router)

app.mount('#app')

六、总结

image.png

  • 33
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pinia 是一个用于 Vue.js 的状态管理库,它提供了一种简单且可扩展的方式来管理应用程序的状态。Pinia-plugin-persistedstate 是一个 Pinia 插件,它可以帮助你将应用程序的状态持久化到本地存储中,以便在刷新页面或重新加载应用程序时保持状态的一致性。 使用 pinia-plugin-persistedstate 插件进行持久化的步骤如下: 1. 安装插件: 你可以使用 npm 或者 yarn 来安装插件: ``` npm install pinia-plugin-persistedstate ``` 或者 ``` yarn add pinia-plugin-persistedstate ``` 2. 导入插件并注册: 在你的应用程序的入口文件中,导入 `pinia-plugin-persistedstate` 并将其注册到 Pinia 实例中: ```javascript import { createApp } from 'vue' import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState()) const app = createApp(App) app.use(pinia) app.mount('#app') ``` 3. 配置插件: 你可以通过传递选项对象来配置插件,例如指定要持久化的状态模块、存储键名等: ```javascript pinia.use(createPersistedState({ key: 'my-app-state', // 存储键名,默认为 'pinia-state' paths: ['counter'], // 要持久化的状态模块,默认为全部模块 storage: localStorage // 存储引擎,默认为 localStorage })) ``` 4. 使用持久化的状态: 在你的组件中,你可以像使用普通的 Pinia 状态一样使用持久化的状态: ```javascript import { useStore } from 'pinia' export default { setup() { const store = useStore() // 读取持久化的状态 console.log(store.counter) // 修改持久化的状态 store.counter++ } } ``` 这样,你就可以使用 pinia-plugin-persistedstate 插件来实现 Pinia 状态的持久化了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值