簡體   English   中英

在 nuxt 可組合項中使用 XState

[英]Use XState in a nuxt composable

我想在 Nuxt 3 中使用 xstate state 機器,它用於多個組件。 我創建了一個小例子來說明我希望它看起來像什么。

我還使用nuxt-xstate模塊。

State 機器:

export default createMachine(
    {
        id: 'toggle',
        initial: 'switched_off',
        states: {
            switched_on: {
                on: {
                    SWITCH: {
                        target: 'switched_off'
                    }
                }
            },
            switched_off: {
                on: {
                    SWITCH: {
                        target: 'switched_on'
                    },
                }
                
            },
        },

    }

)

可組合:

const toggle = useMachine(toggleMachine)

export function useToggleMachine(){
    return { toggle }
}

應用程序.vue:

<template>
  <div>
    State: {{toggle.state.value.value}}
  </div>
  <br />
  <button
    @click="toggle.send('SWITCH')"
  >
      Switch
  </button>
</template>

<script>
    import { useToggleMachine } from '~/composables/toggle_machine'
    export default { 
        setup(){
            const { toggle } = useToggleMachine()


            return { toggle }
        }
    }
</script>

問題是,我可以查看機器 {{state.value.value}} 的 state 給了我預期的“turned_off”。 但是我不能將事件稱為狀態之間的轉換。 單擊按鈕時,沒有任何反應。

這是傳遞的“切換”object 的 console.log:

在此處輸入圖像描述

有誰知道如何解決這個問題,或者如何在多個組件上使用 xstate state 機器。 我知道 props 有效,但我真的不想采用這樣的分層方法。

在 Nuxt3 中,這很簡單:

composables/states.ts

import { createMachine, assign } from 'xstate';
import { useMachine } from '@xstate/vue';

const toggleMachine = createMachine({
  predictableActionArguments: true,
  id: 'toggle',
  initial: 'inactive',
  context: {
    count: 0,
  },
  states: {
    inactive: {
      on: { TOGGLE: 'active' },
    },
    active: {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      entry: assign({ count: (ctx: any) => ctx.count + 1 }),
      on: { TOGGLE: 'inactive' },
    },
  },
});
export const useToggleMachine = () => useMachine(toggleMachine);

pages/counter.vue

<script setup>
const { state, send } = useToggleMachine()
</script>

<template>
  <div>
    <button @click="send('TOGGLE')">
      Click me ({{ state.matches("active") ? "✅" : "❌" }})
    </button>
    <code>
      Toggled
      <strong>{{ state.context.count }}</strong> times
    </code>
  </div>
</template>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM