全局状态管理工具 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)
- 这是要是用 store 中的内容直接结构就可以,但是直接结构的话他不是响应式的
-
实例中使用
<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) {
}
}
}