与 Svelte 一起使用

XState integrates great with Svelte, and especially Svelte stores!

The only gotcha is that you’ll need this extra package.

  1. npm install @rollup/plugin-replace --save-dev

Import the new package in rollup.config.js

  1. import replace from '@rollup/plugin-replace';

Then add this to the plugins array in rollup.config.js.

  1. replace({
  2. 'process.env.NODE_ENV': process.env.NODE_ENV
  3. });

machine.js

  1. import { createMachine } from 'xstate';
  2. // This machine is completely decoupled from Svelte
  3. export const toggleMachine = createMachine({
  4. id: 'toggle',
  5. initial: 'inactive',
  6. states: {
  7. inactive: {
  8. on: { TOGGLE: 'active' }
  9. },
  10. active: {
  11. on: { TOGGLE: 'inactive' }
  12. }
  13. }
  14. });

App.svelte - Standard usage

  1. <script>
  2. import {interpret} from 'xstate';
  3. import {toggleMachine} from './machine';
  4. let current;
  5. const toggleService = interpret(toggleMachine)
  6. .onTransition((state) => {
  7. current = state;
  8. }).start()
  9. </script>
  10. <button on:click={() => toggleService.send('TOGGLE')}>
  11. {current.matches('inactive') ? 'Off' : 'On'}
  12. </button>

App.svelte - Store usage

The toggleService has a .subscribe function that is similar to Svelte stores, so it can be used as a readable store.

  1. <script>
  2. import {interpret} from 'xstate';
  3. import {toggleMachine} from './machine';
  4. const toggleService = interpret(toggleMachine).start();
  5. </script>
  6. <button on:click={() => toggleService.send('TOGGLE')}>
  7. {$toggleService.matches('inactive') ? 'Off' : 'On'}
  8. </button>

If you’re not familiar with the ‘\$’ syntax, it basically just reads the value of a store.