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>
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/4335661