8000 update plugins doc · poorprogrammer/vuejs.org@b6c4702 · GitHub
[go: up one dir, main page]

Skip to content

Commit b6c4702

Browse files
committed
update plugins doc
1 parent 5385d41 commit b6c4702

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/en/plugins.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,39 @@ const store = new Vuex.Store({
2323
})
2424
```
2525

26+
### Dispatching Inside Plugins
27+
2628
Plugins are not allowed to directly mutate state - similar to your components, they can only trigger changes by dispatching mutations.
2729

30+
By dispatching mutations, a plugin can be used to sync a data source to the store. For example, to sync a websocket data source to the store (this is just a contrived example, in reality the `createPlugin` function can take some additional options for more complex tasks):
31+
32+
``` js
33+
export default function createWebSocketPlugin (socket) {
34+
return store => {
35+
socket.on('data', data => {
36+
store.dispatch('RECEIVE_DATA', data)
37+
})
38+
store.on('mutation', (mutation) => {
39+
if (mutation.type === 'UPDATE_DATA') {
40+
socket.emit('update', mutation.payload)
41+
}
42+
})
43+
}
44+
}
45+
```
46+
47+
``` js
48+
const plugin = createWebSocketPlugin(socket)
49+
50+
const store = new Vuex.Store({
51+
state,
52+
mutations,
53+
plugins: [plugin]
54+
})
55+
```
56+
57+
### Taking State Snapshots
58+
2859
Sometimes a plugin may want to receive "snapshots" of the state, and also compare the post-mutation state with pre-mutation state. To achieve that, you will need to perform a deep-copy on the state object:
2960

3061
``` js

0 commit comments

Comments
 (0)
0