Vue 全局状态管理工具 pinia

10 篇文章 0 订阅

全局状态管理工具 pinia

  • 本文的使用时针对于 Vue3 来展开的

  • 当然了项目是是基于 vite 创建的

  • 其他请跳转,pinia 的官方文档

  • 其实有 vuex 的基础 pinia 使用起来会非常简单

一、下载 pinia

npm install pinia

二、引入 pinia

  • 在 main.js 中引入
    import { createPinia } from 'pinia'
  • 在该 vue 实例中使用
    app.use(createPinia())

三、创建一个简单的 store

  • 和 vuex 一样先创建一个 store 文件夹

  • store 是通过 defineStore() 定义的。使用的话先引入
    import { defineStore } from 'pinia'

  • 创建一个全局的变量

    // src/stores/counterStore
    import { defineStore } from "pinia";
    // defineStore 函数返回值本质是一个Hooks
    export const useCounterStore = defineStore("counter", {
      // 数据管理
      state: () => ({
        count: 0,
      }),
    
      //方法
      actions: {
        increment() {
          this.count++;
        },
      },
    
      // 计算属性
      getters: {
        doubleCount() {
          return this.count * 2;
        },
      },
    });
    

四、在页面中使用 store

  • 在页面中引入 store
    import { useCounterStore } from "@/stores/counterStore"

  • 使用 该 store
    const counterStore = useCounterStore()

    • 这是要是用 store 中的内容直接结构就可以,但是直接结构的话他不是响应式的
      const { count, doubleCount } = counterStore
    • 这是就要用到一个方法 storeToRefs() 使得从 Store 中提取属性同时保持其响应式
      const { count, doubleCount } = storeToRefs(counterStore)
  • 实例中使用

    <template>
      <div>
        {{ count }} {{ doubleCount }}
        <button @click="couterStore.increment">+</button>
      </div>
    </template>
    
    <script setup>
      import {storeToRefs} from 'pinia' import {useCounterStore} from
      '@/stores/counterStore' const couterStore = useCounterStore() const{" "}
      {(count, doubleCount)} = storeToRefs(couterStore)
    </script>
    

五、pinia 的模块化

  • pinia 的模块是就是创建多个独立的 store 实例
  • 相互访问的方法和在页面中使用的方法也是一样的

六、pinia 的异步操作

  • pinia 的异步操作和 vuex 不一样,没有单独拆分一个方法出来处理
  • pinia 的异步方法处理还是在 actions 里面,使用 async 和 await,配合 try 和 catch
// 模拟一个异步方法 catchDataApi()
  actions: {
    async loadData() {
      try {
        const data = await catchDataApi()
        this.products = data
      } catch (error) {

      }
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值