forked from vuejs-tips/vuex-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.example.js
91 lines (77 loc) · 2.17 KB
/
store.example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
todos: []
},
getters: {
doneTodos (state, getters, rootState) {
return state.todos.filter(todo => todo.done)
},
getTodoById: (state, getters, rootState) => (id) => {
return state.todos.find(todo => todo.id === id)
},
getTodoById (state, getters, rootState) {
return id => state.todos.find(todo => todo.id === id)
}
},
mutations: {
addTodo (state, payload) {
state.todos.push(payload)
}
},
actions: {
addTodoSync (context, payload) {
context.commit('addTodo', payload)
},
addTodoAsync ({commit}, payload) {
return remoteApi.addTodo(payload)
.then(todo => commit('addTodo', todo))
}
}
})
________________________________________________________________________________________________________________________
// https://vuex.vuejs.org/en/intro.html (imagem)
// <script src="https://unpkg.com/vuex@2.0.0"></script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
computed: {
// this.size
...mapState(['size']),
// alias this.length
...mapState({length: 'size'}),
// functions
...mapState({
// fat arrow
count: state => state.count,
// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
return state.count + this.localCount
}
}),
// getters
...mapGetters([
'doneTodosCount', // same as this.$store.
doneCount: 'doneTodosCount' // alias
])
},
methods: {
// map this.increment() to this.$store.commit('increment')
...mapMutations(['increment']),
// map this.add() to this.$store.commit('increment')
...mapMutations({add: 'increment'}),
// Actions
...mapActions([
// this.addTodo() maps to this.$store.dispatch('addTodo')
'addTodo',
// this.incrementBy(amount) maps to this.$store.dispatch('incrementBy', amount)
'incrementBy'
]),
// this.add() maps to this.$store.dispatch('increment')
...mapActions({
add: 'increment'
})
}
}