# 与 Svelte 一起使用

¥Usage with Svelte

这将指导你在 Svelte 项目中设置 XState。对于新的 Svelte 或 SvelteKit 项目,我们建议使用 Vite (opens new window) 作为构建工具,并且我们已针对此类项目定制了本文档。如果你正在开发依赖于 Rollup 的旧项目,请参阅下面的 基于 Rollup 部分的旧版 Svelte 项目

¥This guides you through setting up XState in a Svelte project. For new Svelte or SvelteKit projects, we recommend using Vite (opens new window) as your build tool, and we’ve tailored this documentation to such projects. If you're working on an older project that relies on Rollup, please refer to the Legacy Svelte projects based on Rollup section below.

# 基于 Vite 的 Svelte 项目

¥Svelte projects based on Vite

XState 与 Svelte 和 SvelteKit,尤其是 Svelte 存储 (opens new window) 集成得很好。我们推荐官方 @xstate/svelte 包以充分利用 XState 和 Svelte。

¥XState integrates great with Svelte & SvelteKit, and especially Svelte stores (opens new window). We recommend the official @xstate/svelte package to get the most out of XState and Svelte.

# 基于 Rollup 的旧版 Svelte 项目

¥Legacy Svelte projects based on Rollup

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

在 rollup.config.js 中导入新包

¥Import the new package in rollup.config.js

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

然后将其添加到 rollup.config.js 中的插件数组中。

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

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

# machine.js

import { createMachine } from 'xstate';

// This machine is completely decoupled from Svelte
export const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});

# App.svelte - 标准用法

¥App.svelte - Standard usage

<script>
  import { interpret } from 'xstate';
  import { toggleMachine } from './machine';

  let current;

  const toggleService = interpret(toggleMachine)
    .onTransition((state) => {
      current = state;
    })
    .start();
</script>

<button on:click="{()" ="">
  toggleService.send({ type: 'TOGGLE' })}> {current.matches('inactive') ? 'Off'
  : 'On'}
</button>

# App.svelte - 存储用法

¥App.svelte - Store usage

toggleService 有一个与 Svelte 存储类似的 .subscribe 功能,因此它可以用作可读存储。

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

<script>
  import { interpret } from 'xstate';
  import { toggleMachine } from './machine';

  const toggleService = interpret(toggleMachine).start();
</script>

<button on:click="{()" ="">
  toggleService.send({ type: 'TOGGLE' })}> {$toggleService.matches('inactive') ?
  'Off' : 'On'}
</button>

如果你不熟悉 '$' 语法,它基本上只是读取存储的值。

¥If you're not familiar with the '$' syntax, it basically just reads the value of a store.