Pinia

204 阅读1分钟

Pinia

  • Pinia:一个拥有 组合式 API 的 Vue 状态管理库

  • pinia 干掉了 mutationsmodules

  • piniastateactionsgetters

    • state:必须写函数返回一个对象
    • actions:可以写同步和异步代码
    • getters:计算属性

全局注册

import { createPinia } from 'pinia'
app.use(createPinia())

配置

🌰:
// 导入
import { defineStore } from 'pinia'
// 使用
export const userStore = defineStore('userStore', {
    state() {
        return {
            name: "张三",
            age: 18
        }
    },
    actions: {
        /* 一定要注意: 不要箭头函数,普通函数的this=>store */
        set_name(params) {
            //可以同步
            this.name = params
        },
        set_age(params) {
            //可以异步
            setTimeout(() => {
                this.age = params
            }, 1000)
        }
    },
    getters:{
        getters_name(){
            return this.name + "真好"
        },
        getters_age(){
            return this.age + "岁"
        }
    }
})

使用

import { userStore } from './stores/userStore.js' // 引入
let store = userStore() // 使用
// 调用actions里的函数
const btn = () => {
    store.set_name("李四")
}
<template>
    <!-- 获取state里的数据 -->
    {{ store.name }}~~{{ store.age }}
	<!-- 获取计算属性 -->
	{{ store.getters_name }}~~{{ store.getters_age }}
</template>