likes
comments
collection
share

Pinia-新一代状态管理工具

作者站长头像
站长
· 阅读数 19

Pinia-新一代状态管理工具

1.Pinia简介

Pinia 是一个状态管理工具,和 Vuex 一样为 Vue 项目提供共享状态管理工具。并且支持vue2和vue3,主要是为vue3提供状态管理,支持typescript。Pinia可以创建多个全局仓库,不用像 Vuex 一个仓库嵌套模块,结构复杂。管理数据简单,提供数据和修改数据的逻辑即可,不像Vuex需要记忆太多的API。

2.Pinia使用

  1. 安装

    pnpm i pinia
    # or
    yarn add pinia
    # or
    npm i pinia
    
  2. 导入使用,当做vue的插件使用

    为了在项目中规范化使用,在src下创建目录stores,并创建index.ts文件

    import { createPinia } from 'pinia'
    
    const pinia = createPinia()
    
    export default pinia
    
    

    main.ts中注册pinia

    import App from './App.vue'
    import { createApp } from 'vue'
    import pinia from './stores/index'
    
    const app = createApp(App)
    app.use(pinia).mount('#app')
    

    stores下创建nodules文件夹,可以分模块使用

    import { defineStore } from 'pinia'
    import { ref } from 'vue'
    
    type User = {
      id: string
      name: string
      age: number
      gender: string
    }
    
    export const useUserStore = defineStore('user', () => {
      // 相当于 vuex 中的 state
      const userInfo = ref<User>({
        id: 'abc',
        name: '张三',
        age: 15,
        gender: '男',
      })
    
      return { userInfo }
    })
    
    
    

    index.ts文件中导入,这样就可以在vue文件中使用了

    export * from './modules/user'
    
  3. 使用

    在vue文件中引用并使用

    import { useUserStore } from './stores/index'
    
    const store = useUserStore()
    
    <span>{{ store.userInfo.name }}</span>
    <span>{{ store.userInfo.age }}</span>
    <span>{{ store.userInfo.gender }}</span>
    

    就可以看到页面显示的内容了,如下图所示: Pinia-新一代状态管理工具

     // 相当于 vuex 中的getters
      const changeAge = computed(() => userInfo.value.age + 5)
    
    <span>年龄:{{ store.changeAge }}</span>
    

    页面上的年龄变成了20,如图所示: Pinia-新一代状态管理工具 mutations

 // 相当于 vuex 中的mutations
  const update = (name: string) => (userInfo.value.name = name)
 <button @click="store.update('李斯')">update</button>

点击页面按钮后,页面上的名字发生了改变 Pinia-新一代状态管理工具 actions

// 相当于 vuex 中的actions 可以做一些异步请求
  const asyncUpdate = (gender: string) => {
    setTimeout(() => {
      userInfo.value.gender = gender
    }, 3000)
  }
<button @click="store.asyncUpdate('女')">asyncUpdate</button>

点击页面按钮后,三秒后页面上的性别发生了改变

总结一下:

  1. 通过const useUserStore = defineStore('id', () => {})创建数据仓库
  2. vuex 中的 state 在 pinia 中可以引用 refreactive 创建响应式数据
  3. vuex 中的 getters 在 pinia 中可以引用 computed 创建计算属性
  4. vuex 中的 mutations 和 actions 在 pinia 中就是普通函数, 同步异步都可以

3. storeToRefs的使用

如果我们想结构 store 提供的数据的时候,发现数据是没有响应式的,所以可以使用storeToRefs 来解决结构仓库状态丢失响应式的问题

import { useUserStore } from './stores/index'
import { storeToRefs } from 'pinia'
const store = useUserStore()

const { userInfo, changeAge } = storeToRefs(store)

4.数据持久化存储(pinia-plugin-persistedstate)

  1. 安装

    pnpm i pinia-plugin-persistedstate
    # or
    yarn add pinia-plugin-persistedstate
    # or
    npm i pinia-plugin-persistedstate
    
  2. 使用

    import { createPinia } from 'pinia'
    import persist from 'pinia-plugin-persistedstate'
    
    const pinia = createPinia()
    pinia.use(persist)
    
    import { defineStore } from 'pinia'
    import { ref, computed } from 'vue'
    
    type User = {
      id: string
      name: string
      age: number
      gender: string
    }
    
    export const useUserStore = defineStore(
      'user',
      () => {
        // 相当于 vuex 中的 state
        const userInfo = ref<User>({
          id: 'abc',
          name: '张三',
          age: 15,
          gender: '男',
        })
    
        // 相当于 vuex 中的getters
        const changeAge = computed(() => userInfo.value.age + 5)
    
        // 相当于 vuex 中的mutations
        const update = (name: string) => (userInfo.value.name = name)
    
        // 相当于 vuex 中的actions 可以做一些异步请求
        const asyncUpdate = (gender: string) => {
          setTimeout(() => {
            userInfo.value.gender = gender
          }, 3000)
        }
    
        return { userInfo, changeAge, update, asyncUpdate }
      },
        // 使用数据持久化
      {
        persist: true,
      }
    )
    
    

    默认是存到localStorge, 可以看到浏览器的 localStorge的数据,键是仓库的id,值是仓库的状态,如图所示:

Pinia-新一代状态管理工具

详细配置方法可参考官方文档:prazdevs.github.io/pinia-plugi…