pinia-state-tree: 一个 pinia 的语法糖

一个 pinia 的语法糖,在 vue3项目中可以更方便的使用 pinia
更新于: 2023-05-25 09:15:18
项目主页: https://github.com/afeiship/pinia-state-tree

安装

yarn add @jswork/pinia-state-tree

用法

下面这个是我用到的示例代码 shared/stores/user.js

import { defineStore } from "pinia";

export default defineStore("user", {
  state: () => ({ username: "aric", profile: null }),
  actions: {
    async login() {
      const res = await nx.$api.profile();
      this.profile = res;
    },
  },
});

Tips: 在实际项目中,可优先学习5星的,其它API,可以忽略。

用法代码常用指数(5)
获取 pinia 实例
nx.$pin
⭐️
获取 app 实例
nx.$app
⭐️
获取 state tree
nx.$get()
⭐️⭐️⭐️
获取 store tree
nx.$query()
⭐️⭐️⭐️
获取 state
nx.$get('user.loading')
⭐️⭐️⭐️⭐️⭐️
设置 state
// 单个
nx.$set('user.loading', true)
// 一次多个
nx.$set({ 'user.loading': true, 'user.profile.login': 'afei' })
⭐️⭐️⭐️⭐️
执行 store 上的方法
await nx.$call('user.login',{ username: 'afei', password: '123123' });
⭐️⭐️⭐️
map 具体的 state到 computed 上
export default {
  //... 省略了7行代码
  computed: {
    ...nx.$map([
      'user.profile.login:username',
      'user.loading'
    ])
  }
};
⭐️⭐️⭐️⭐️⭐️