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

本文详细介绍了Pinia在Vue项目中的安装、注册、Store的定义(OptionStore和SetupStore)、数据持久化以及模块管理。重点讲解了如何使用Pinia实现状态管理,并提供了不同语法的选择和配置存储库的示例。
摘要由CSDN通过智能技术生成

一、什么是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

对于Pinia的安装与配置,您可以按照以下步骤进行操作: 1. 首先,确保您已经安装了Node.js和npm。您可以在终端中运行以下命令来检查是否已安装: ``` node -v npm -v ``` 2. 创建一个新的Vue项目,可以使用Vue CLI或手动创建。在终端中执行以下命令进行创建: ``` vue create my-project ``` 3. 进入项目目录,并使用npm安装Pinia: ``` cd my-project npm install pinia ``` 4. 在项目的入口文件(通常是`src/main.js`)中导入和使用Pinia。您可以按照以下方式进行配置: ```javascript import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) const pinia = createPinia() app.use(pinia) app.mount('#app') ``` 5. 现在,您可以在整个应用程序中使用Pinia提供的状态管理功能。您可以创建一个store并在组件中使用它。例如,创建一个名为`counter`的store: ```javascript import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), actions: { increment() { this.count++ }, decrement() { this.count-- }, }, }) ``` 6. 在组件中使用store时,您可以使用`useStore`函数进行访问: ```javascript import { useCounterStore } from '@/stores/counter' export default { setup() { const counterStore = useCounterStore() return { counterStore, } }, } ``` 这样,您就可以安装和配置Pinia,并在Vue应用程序中使用它来进行状态管理了。请注意,这只是一个简单的示例,您可以根据自己的需求进行更详细的配置和使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值