xstate 状态管理 vue3 模拟红绿灯

萝らか妹 提交于 2020-10-06 03:12:40

https://github.com/davidkpiano/xstate/tree/master/packages/core#readme

https://blog.jerry-hong.com/posts/xstate-tutorials-state-machine/

 

安装

yarn add xstate

配合vue模拟红绿灯

 

<template>
  <div :style="`background:${state}`">{{ state }}</div>
  <button @click="click">click</button>
</template>

<script>
import { createMachine, interpret } from "xstate";
import { reactive, ref } from "vue";
export default {
  name: "App",
  setup() {
    const states = {
      green: { on: { TOGGLE: "yellow" } },
      yellow: { on: { TOGGLE: "red" } },
      red: { on: { TOGGLE: "green" } },
    };

    const state = ref("green");
    const toggleMachine = createMachine({
      id: "toggle",
      initial: state.value,
      states,
    });
    const toggleService = interpret(toggleMachine)
      .onTransition((newState) => {
        console.log(newState.value);
        state.value = newState.value;
      })
      .start();
    const click = () => toggleService.send("TOGGLE");
    return {
      click,
      state,
    };
  },
};
</script>

 

 

vue hook 版

官方hook, 简洁很多

<template>
  <button @click="send('TOGGLE')">
    {{
      state.value === 'inactive'
        ? 'Click to activate'
        : 'Active! Click to deactivate'
    }}
  </button>
</template>

<script>
import { useMachine } from '@xstate/vue';
import { Machine } from 'xstate';

const toggleMachine = Machine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});

export default {
  setup() {
    const { state, send } = useMachine(toggleMachine);
    return {
      state,
      send
    };
  }
};
</script>

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!