与 Vue 一起使用

If you want to use the Vue Composition API, we recommend using the following packages:

Vue follows a similar pattern to React:

  • The machine can be defined externally;
  • The service is placed on the data object;
  • State changes are observed via service.onTransition(state => ...), where you set some data property to the next state;
  • 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 is created();
  • Events are sent to the service via service.send(event).
  1. import { createMachine } from 'xstate';
  2. // This machine is completely decoupled from Vue
  3. export const toggleMachine = createMachine({
  4. id: 'toggle',
  5. context: {
  6. /* some data */
  7. },
  8. initial: 'inactive',
  9. states: {
  10. inactive: {
  11. on: { TOGGLE: 'active' }
  12. },
  13. active: {
  14. on: { TOGGLE: 'inactive' }
  15. }
  16. }
  17. });
  1. <!-- Toggle.vue -->
  2. <template>
  3. <button v-on:click="send('TOGGLE');">
  4. {{ current.matches("inactive") ? "Off" : "On" }}
  5. </button>
  6. </template>
  7. <script>
  8. import { interpret } from 'xstate';
  9. import { toggleMachine } from '../path/to/toggleMachine';
  10. export default {
  11. name: 'Toggle',
  12. created() {
  13. // Start service on component creation
  14. this.toggleService
  15. .onTransition((state) => {
  16. // Update the current state component data property with the next state
  17. this.current = state;
  18. // Update the context component data property with the updated context
  19. this.context = state.context;
  20. })
  21. .start();
  22. },
  23. data() {
  24. return {
  25. // Interpret the machine and store it in data
  26. toggleService: interpret(toggleMachine),
  27. // Start with the machine's initial state
  28. current: toggleMachine.initialState,
  29. // Start with the machine's initial context
  30. context: toggleMachine.context
  31. };
  32. },
  33. methods: {
  34. // Send events to the service
  35. send(event) {
  36. this.toggleService.send(event);
  37. }
  38. }
  39. };
  40. </script>