项目作者: jhony-24

项目描述 :
Light State management based in atoms for Vue 3
高级语言: TypeScript
项目地址: git://github.com/jhony-24/vue-atom.git
创建时间: 2021-05-08T20:59:42Z
项目社区:https://github.com/jhony-24/vue-atom

开源协议:

下载


vue-atom

State management based in atoms to Vue 3.

Using store atoms

Creating stores

  1. import { atom } from "vue-atom";
  2. const usernameAtom = atom("jhon");
  3. const postsAtom = atom([]);

Writing getters

  1. import { selector } from "vue-atom";
  2. const usernameModified = selector(get => get(usernameAtom).toUpperCase());

Updating the stores

To update an atom we use a callback method instead of a value

  1. import { atom } from "vue-atom";
  2. // Update the username
  3. const changeUsername = atom((set, _get, payload) => {
  4. set(usernameAtom, payload);
  5. });
  6. // Update async store
  7. const getPosts = atom(async (set) => {
  8. const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  9. const json = await response.json();
  10. set(postsStore,json);
  11. });

Listening when the atom is updated

You can use the .subscribe method of atom to listen all changes

  1. usernameAtom.subscribe(value => {
  2. console.log(value)
  3. })

Using in vue components

To use a store o selector use useAtoms(), for actions use useActions().

  1. <template>
  2. <section>
  3. <h1>{{ username }} - {{ usernameUppercase }}</h1>
  4. <button @click="actions.changeUsername('marcos')">
  5. Change username
  6. </button>
  7. </section>
  8. </template>
  9. <script>
  10. import { useAtom, useAction } from "vue-atom";
  11. export default {
  12. setup() {
  13. const usernaame = useAtom(usernameAtom);
  14. const usernameUppercase = useAtom(usernameModified);
  15. const actions = useAction({ changeUsername });
  16. return {
  17. username,
  18. usernameUppercase,
  19. actions,
  20. };
  21. },
  22. };
  23. </script>

If you want to use multiple stores or selectors with a one useAtoms hooks you can pass how object

  1. <template>
  2. <section>
  3. <h1>{{ state.username }} - {{ state.uppercase }}</h1>
  4. <button @click="actions.changeUsername('marcos')">
  5. Change username
  6. </button>
  7. </section>
  8. </template>
  9. <script>
  10. import { useAtom, useAction } from "vue-atom";
  11. export default {
  12. setup() {
  13. const state = useAtom({
  14. username : usernameAtom,
  15. uppercase : usernameModified
  16. });
  17. const actions = useAction({ changeUsername });
  18. return {
  19. state,
  20. actions,
  21. };
  22. },
  23. };
  24. </script>

API

atom()

Initialize a store with value or create an action.

selector()

Get a new value of atoms.

useAtom()

Get a object of atoms.

useAction()

Get multiple actions or one action.