[英]When Can I Use A Composable in the Scope of a LazyList or Column?
[英]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.