Pinia使用总结

131 阅读2分钟

一、Pinia是什么

Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。与Vuex相比,Pinia 不仅提供了一个更简单的 API,也提供了符合组合式API风格的API,最重要的是,搭配TypeScript一起使用时有非常可靠的类型推断支持。

二、为什么要使用Pinia?

  • Pinia中只有state、getter、action,抛弃了Vuex中的Mutation,Vuex中mutation一直都不太受小伙伴们的待见,pinia直接抛弃它了,这无疑减少了我们工作量。
  • Pinia中action支持同步和异步,Vuex不支持
  • 轻巧(体积约 1KB)
  • 插件:可通过插件扩展 Pinia 功能
  • 为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。
  • 支持服务端渲染

三、pinia的核心属性

1、State

  • State是应用程序定义初始化状态的容器,在 Pinia 中,状态被定义为返回初始状态的函数。 这允许 Pinia 在服务器端和客户端工作。
const useUserStore = defineStore('user', {
    state: () => ({
        firstName: 'Liu',
        lastName: 'Dehua'
    }),
})

2、# Getters

  • Getter 完全等同于 Store 状态的 [计算值] 它们可以用 defineStore() 中的 getters 属性定义
const useUserStore = defineStore('user', {
    state: () => ({
        name: '李四',
        age: 18
    }),
    getters: {
        getInfo() {
            return this.name + '的年龄:' + this.age
        }
    },
})

3、# Actions

  • Actions 相当于组件中的 [methods]。 它们可以使用 defineStore() 中的 actions 属性定义,并且它们非常适合定义业务逻辑
import { defineStore } from "pinia"
const useUserStore = defineStore('user', {
    state: () => ({
        name: '李四',
        age: 18
    }),
    getters: {
        getInfo() {
            return this.name + '的年龄:' + this.age
        }
    },
    actions: {
        updateName(newName) {
            this.name = newName
        }
    },
})
export default useUserStore

四、pinia在vue中的使用

<template>
  <div class="about">
    <div class="store">
      <h1>在组件中您可以这样使用定义的Store</h1>
      <h2>name:{{ name }}</h2>
      <h2>age:{{ age }}</h2>
    </div>
  </div>
</template><script setup lang="ts">
import useUserStore from '@/stores/modules/user'
//对于pinia中拿来的数据若直接解构,不处理,数据就会丢失响应式
//此时需使用storeToRefs
import { storeToRefs } from 'pinia'
const userStore = useUserStore()
const { name, age } = storeToRefs(userStore)
</script>