Vuex Store Namespaced Modules

by Admiral Potato

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<div id="app">
<h1>Time is now: {{ time }}</h1>
<div>
	<button
		@click="$store.dispatch('time/update')"
	>Update time</button>
</div>
<h2>Is it Goat Time?: {{ goats }}</h2>
<div>
<label>
	<span>Goats?</span>
	<input
		type="checkbox"
		v-model="goats"
	/>
</label>
</div>
</div>

JavaScript

const time = {
	namespaced: true,
	state: {
		now: 'no it isnt'
	},
	mutations: {
		TICK (state) {
			state.now = new Date().toJSON()
		}
	},
	actions: {
		update ({ commit }) {
			commit('TICK')
		}
	}
}

const store = new Vuex.Store({
	state: {
		goats: true
	},
	mutations: {
		SET_GOATS (state, payload) {
			state.goats = payload
		}
	},
	modules: {
		time
	}
})

const app = new Vue({
	el: '#app',
	store,
	computed: {
		time () {
			return this.$store.state.time.now
		},
		goats: {
			get () {
				return this.$store.state.goats
			},
			set (value) {
				return this.$store.commit('SET_GOATS', value)
			}
		}
	}
})