与 Vue 一起使用
If you want to use the Vue Composition API, we recommend using the following packages:
@xstate/vuepackage for Vue 3xstate-vue2package (3rd-party) for Vue 2
Vue follows a similar pattern to React:
- The machine can be defined externally;
- The service is placed on the
dataobject; - State changes are observed via
service.onTransition(state => ...), where you set some data property to the nextstate; - The machine’s context can be referenced as an external data store by the app. Context changes are also observed via
service.onTransition(state => ...), where you set another data property to the updated context; - The service is started (
service.start()) when the component iscreated(); - Events are sent to the service via
service.send(event).
import { createMachine } from 'xstate';// This machine is completely decoupled from Vueexport const toggleMachine = createMachine({id: 'toggle',context: {/* some data */},initial: 'inactive',states: {inactive: {on: { TOGGLE: 'active' }},active: {on: { TOGGLE: 'inactive' }}}});
<!-- Toggle.vue --><template><button v-on:click="send('TOGGLE');">{{ current.matches("inactive") ? "Off" : "On" }}</button></template><script>import { interpret } from 'xstate';import { toggleMachine } from '../path/to/toggleMachine';export default {name: 'Toggle',created() {// Start service on component creationthis.toggleService.onTransition((state) => {// Update the current state component data property with the next statethis.current = state;// Update the context component data property with the updated contextthis.context = state.context;}).start();},data() {return {// Interpret the machine and store it in datatoggleService: interpret(toggleMachine),// Start with the machine's initial statecurrent: toggleMachine.initialState,// Start with the machine's initial contextcontext: toggleMachine.context};},methods: {// Send events to the servicesend(event) {this.toggleService.send(event);}}};</script>
