@xstate/vue
@xstate/vue 包 包含了用于在 Vue 中使用 XState 的工具。
模板
使用以下模板可以快速开始使用 XState 和 Vue:
安装
安装最新版本的 xstate 和 @xstate/vue。xstate 是 @xstate/vue 的一个 peer 依赖。
- npm
- pnpm
- yarn
npm install xstate @xstate/vue
pnpm install xstate @xstate/vue
yarn add xstate @xstate/vue
API
useActor(actorLogic, options?)
一个 Vue 组合函数,它从给定的 actorLogic 创建一个 actor,并启动一个在组件生命周期内运行的 actor 引用。
参数
actorLogic- 一个 XState 状态机options(可选) - Actor 选项
返回 { snapshot, send, actorRef }:
snapshot- 表示状态机的当前快照(状态),作为 XStateState对象。send- 一个向运行中的 actor 发送事件的函数。actorRef- 创建的 actor 引用。
useMachine(machine, options?)
一个 Vue 组合函数,它从给定的 machine 创建一个 actor,并启动一个在组件生命周期内运行的 actor。
参数
machine- 一个 XState 状态机options(可选) - Actor 选项
返回 { snapshot, send, actorRef }:
snapshot- 表示状态机的当前快照(状态),作为 XStateState对象。send- 一个向运行中的 actor 发送事件的函数。actorRef- 创建的 actor 引用。
useActorRef(actorLogic, options?, observer?)
一个 Vue 组合函数,它返回从 actorLogic 创建的 actorRef,并带有指定的 actor options(如果有)。如果提供了 observer,它还会设置对 actorRef 的订阅。
参数
actorLogic- Actor 逻辑options(可选) - Actor 选项observer(可选) - 一个监听快照更新的观察者或监听器:- 一个观察者(例如,
{ next: (snapshot) => {/* ... */} }) - 或一个监听器(例如,
(snapshot) => {/* ... */})
- 一个观察者(例如,
示例
import { useActorRef } from '@xstate/vue';
import { someMachine } from '../path/to/someMachine';
export default {
setup() {
const actorRef = useActorRef(someMachine);
return actorRef;
},
};
带选项和监听器:
import { useInterpret } from '@xstate/vue';
import { someMachine } from '../path/to/someMachine';
export default {
setup() {
const actor = useInterpret(
someMachine,
{
actions: {
/* ... */
},
},
(state) => {
// 订阅状态变化
console.log(state.value);
},
);
// ...
},
};
useSelector(actor, selector, compare?, getSnapshot?)
一个 Vue 组合函数,它从 actorRef 的快照中返回选定的值,例如一个 actor。只有在选定的值发生变化时,此钩子才会导致重新渲染,这由可选的 compare 函数确定。
参数
actorRef- 一个 actor 或类似 actor 的对象,包含.send(...)和.subscribe(...)方法。selector- 一个函数,它将 actor 的“当前状态”(快照)作为参数,并返回所需的选定值。compare(可选) - 一个函数,用于确定当前选定的值是否与之前的选定值相同。getSnapshot(可选) - 一个函数,应返回actorRef的最新发出值。- 默认情况下尝试获取
actor.state,如果不存在则返回undefined。将自动从 actor 中提取状态。
- 默认情况下尝试获取
import { useSelector } from '@xstate/vue';
const selectCount = (snapshot) => snapshot.context.count;
export default {
props: ['actor'],
setup(props) {
const count = useSelector(props.actor, selectCount);
// ...
return { count };
},
};
使用 compare 函数:
import { useSelector } from '@xstate/vue';
const selectUser = (state) => state.context.user;
const compareUser = (prevUser, nextUser) => prevUser.id === nextUser.id;
export default {
props: ['actor'],
setup(props) {
const user = useSelector(props.actor, selectUser, compareUser);
// ...
return { user };
},
};
使用 useActorRef(...):
import { useActorRef, useSelector } from '@xstate/vue';
import { someMachine } from '../path/to/someMachine';
const selectCount = (snapshot) => snapshot.context.count;
export default {
setup() {
const actorRef = useActorRef(someMachine);
const count = useSelector(actorRef, selectCount);
// ...
return { count, actorRef };
},
};