export const state = () => ({
counter: 0
})export const mutations = {
increment (state) {
state.counter++
}
}
其他的模块文件也需要采用类似的方式,如
store/todos.js文件:
export const state = () => ({
list: []})export const mutations = {
add (state, text) {
state.list.push({
text: text,
done: false
})
},
remove (state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle (state, todo) {
todo.done = !todo.done
}
}
在页面组件
pages/todos.vue, 可以像下面这样使用
todos模块:
<template>
<ul>
<li v-for="todo in todos">
<input type="checkbox" :checked="todo.done" @change="toggle(todo)">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
</li>
<li><input placeholder="What needs to be done?" @keyup.enter="addTodo"></li>
</ul>
</template><script>
import { mapMutations } from 'vuex'
export default {
computed: {
todos () { return this.$store.state.todos.list }
},
methods: {
addTodo (e) {
this.$store.commit('todos/add', e.target.value)
e.target.value = ''
},
...mapMutations({
toggle: 'todos/toggle'
})
}
}
</script>
<style>
.done {
text-decoration: line-through;
}
</style>
模块方法也适用于顶级定义,而无需在
store目录中实现子目录state 示例,您需要创建一个文件
store/state.js并添加以下内容:
export default () => ({
counter: 0
})并且相应的 mutations 在文件
store/mutations.js中:
export default {
increment (state) {
state.counter++
}
}模块文件
您可以将模块文件分解为单独的文件:
state.js,
actions.js,
mutations.js和
getters.js。如果您使用
index.js来维护
state,
getters










