The proposed changes below are tentative and subject to change.
- Replace middlewares with a more generic plugin system. The store instance will emit events and a plugin is simply a function that receives the store as the only argument.
Example logger plugin:
js
export default function loggerPlugin (store) {
let prevState
store.on('beforeMutation', (mutation, state) => {
prevState = JSON.parse(JSON.stringify(state))
})
store.on('mutation', (mutation, state) => {
console.log('previous state:', prevState)
console.log(`mutation ${mutation.type} triggered`)
console.log('next state:', state)
})
}
A plugin can also be used to sync a data source to the store via dispatch. For example, to sync a web socket data source to the store (this is just a simplified example, in reality the createPlugin function can take some additional options for more complex tasks):
js
export default function createWebSocketPlugin (socket) {
return store => {
socket.on('data', data => {
store.dispatch('RECEIVE_DATA', data)
})
store.on('mutation', (mutation) => {
if (mutation.type === 'UPDATE_DATA') {
socket.emit('update', mutation.payload)
}
})
}
}
``` js
const plugin = createWebSocketPlugin(socket)
const store = new Vuex.Store({
state,
mutations,
plugins: [plugin]
})
```
type Module = {
state?: { [key: string]: any },
mutations?: { [key: string]: Function },
modules?: { [key: string]: Module }
}
logger plugin is simply awesome!
Most helpful comment
See https://github.com/vuejs/vuex/releases/tag/v1.0.0-rc