Vue3.x 集成Pinia 状态管理

3/29/2022

# 前言

  • 为什么要使用 Pinia?

答:异步操作和同步操作不用分 actions, mutations,在Pinia中,统一在 actions 中使用;多个state不需要设置多个module,只需要创建不同的store即可;对TS有更好的兼容性;服务器端的渲染支持

# 安装 Pinia


yarn add Pinia

# 使用

# 创建 src/store 路径(或手动创建)


cd src && mkDir store && cd store

# 创建对应的store文件(或手动创建)


type nul>useMainStore.js //windows命令

内容如下:

// useMainStore.js

// 引入
import { defineStore } from 'pinia'

// 定义store :defineStroe有两个参数,
// 第一个参数storeID(随便取,一般为对应业务的名)
// 第二个参数是一个对象,在里声明 state,getters,actions 
export const useMainStore = defineStore('main', {
    // state
    state: () => {
        // 定义state 属性
        return {
            name:'JunQiu',
            age:20,
            count:10
        }
    },

    // getters
    getters: {

    },

    // actions
    actions: {

    }
})

# 注册 Pinia

// main.js
import { createPinia } from 'pinia'

app.use(createPinia())

app.mount('#app')

# 在对应的文件中引入store文件

//  App.vue
<script setup>
import { storeToRefs } from "pinia";
import { useMainStore } from "./store/useMainStore";

// 引入state中定义的属性
const { name, age, count } = storeToRefs(useMainStore());
</script>
<template>
  <img alt="Vue logo" src="./assets/logo.png" />

  <h1>useMainStore</h1>
  <span>{{ name }} -- {{ age }} -- {{ count }}</span>
</template>

效果图

Last Updated: 3/15/2024, 2:13:06 PM