工程目录
主要关注store 文件夹下的文件
store/index.js
import Vue from 'vue' import Vuex from 'vuex' // import getters from './store/getters.js' // import actions from './store/actions.js' // import mutations from './store/mutations.js' import types from './types' // children module import users from './modules/users.js' Vue.use(Vuex) const state = { count: 1 } const mutations = { [types.INCREMENT]: (state, n) => { state.count = state.count + n }, [types.DECREMENT]: (state, n) => { state.count = state.count - n } } const actions = { increment: (context, n = 1) => { context.commit(types.INCREMENT, n) }, decrement: (context, commit, n = 1) => { context.commit(types.DECREMENT, n) } } export default new Vuex.Store({ state, mutations, actions, modules: { users } })
store/modules/users.js
import types from '../types' const state = { username: 'xiaojf' } const mutations = { [types.CHANGEUSERNAME]: (state, username) => { state.username = username } } const actions = { changeUsername (context, username = 'zhangsan') { context.commit(types.CHANGEUSERNAME, username) } } export default { state, mutations, actions }
/components/test.vue
<template> <div> <div class="test">{{name}}</div> <div class="test">{{this.$store.state.count}}</div> <button v-on:click="increment()">increment</button> <button v-on:click="decrement()">decrement</button> <br> this is users module state <span style="color: red;" v-on:click="changeUsername()"> {{this.$store.state.users.username}}</span> <br> <test2></test2> </div> </template> <script> import test2 from './test2' export default { name: 'test', data: function () { return { name: 'xiaojf' } }, components: { test2 }, methods: { increment () { // mutation this.$store.dispatch('increment', 1) }, decrement () { // action this.$store.dispatch('decrement', 2) }, changeUsername () { // children module's action this.$store.dispatch('changeUsername', 'xiaojianfeng') } } } </script> <style scoped> .test { font-size: 28px; color: red; } </style>
/components/test.vue
<template> <div> this is test2 {{this.$store.state.count}} </div> </template> <script> export default { name: 'test2', data: function () { return { name: 'xiaojf' } } } </script>