//store.js
import { assign, createMachine, interpret } from 'xstate'
import { useActor } from '@xstate/vue'
const counterMachine = createMachine({
id: 'counter',
context: {
count: 0,
},
initial: 'idle',
states: {
idle: {
on: {
INCREMENT: {
actions: assign({
count: (context: { count: number }) => context.count + 1,
}),
},
DECREMENT: {
actions: assign({
count: (context: { count: number }) => context.count - 1,
}),
},
},
},
},
})
const service = interpret(counterMachine).start()
export const useToggleMachine = () => {
return useActor(service)
}
const service = interpret(counterMachine).start()
export const useToggleMachine = () => {
return useActor(service)
}
//A.vue
<template>
<div>
{{ state.context.count }}
<button @click="send('INCREMENT')">+++</button>
//当a页面点击这两个按钮时state.context.count就进行了更新,b页面也就可以看到最新的state.context.count
<button @click="send('DECREMENT')">----</button>
</div>
</template>
<script>
import { useToggleMachine } from '@/store/count'
const { state, send } = useToggleMachine()
console.log(state.value.context)
</script>
//B.vue
<template>
<div>
{{ state.context.count }}
</div>
</template>
<script>
import { useToggleMachine } from '@/store/count'
const { state, send } = useToggleMachine()
</script>