Skip to content

Instantly share code, notes, and snippets.

@toast38coza
Created September 14, 2016 09:38
Show Gist options
  • Save toast38coza/80bf55cda6ea6a05b6aeb0f12d558b74 to your computer and use it in GitHub Desktop.
Save toast38coza/80bf55cda6ea6a05b6aeb0f12d558b74 to your computer and use it in GitHub Desktop.
vuex-counter-plain-old-javascript

A Simple Vuex example in old-skool JavaScript

Because learning all the things: new framework (Vue), new Architecture (Flux), new JavaScript (ES6), new build tools (Browserify, WebPack) all in one can be a little daunting ...

I've kept the below example as simple and bare-bones as possible. One html file with everything you need. You can simply open index.html in your favorite browser to see it in action.

Or, if you want to run it with a server:

python -m SimpleHTTPServer 8000

Then: http://localhost:8000.

<!--
A super simple Plain Old JavaScript rendition of:
http://vuex.vuejs.org/en/tutorial.html
-->
<html>
<body>
<div id="app">
<Increment></Increment>
<Display></Display>
</div>
<!-- templates -->
<template id="display" >
<div>
<h3>Count is {{counterValue}}</h3>
</div>
</template>
<template id="increment" >
<div>
<button v-on:click="increment" >+</button>
</div>
</template>
<script src="./vue.min.js" ></script>
<script src="./vuex.min.js" ></script>
<script>
/* Store */
var state = {
count: 0
}
var mutations = {
INCREMENT: function (state, count){
state.count += count;
}
};
var vstore = new Vuex.Store({
state: state,
mutations: mutations
});
/* ------------------------------------------ */
//actions:
var incrementCounter = function ($event) {
$event.dispatch('INCREMENT', 1); // <- you can change this to increment in different steps this will be the `count` argument in the INCREMENT mutation above
}
/* ------------------------------------------ */
// getters:
var getCount = function (state) {
return state.count;
}
/* ------------------------------------------ */
/* Components */
Vue.component('Increment', {
template: '#increment',
vuex: {
actions: {
increment: incrementCounter // call action above
}
}
});
Vue.component('Display', {
template: '#display',
vuex: {
getters: {
counterValue: getCount // call getter above
}
}
});
/* ------------------------------------------ */
/* Vuex */
var vm = new Vue({
el: '#app',
store: vstore // <- pass the store to our vuex app
});
</script>
</body>
</html>
@toast38coza
Copy link
Author

Note: you'll need vue.js and vuex.js in the same directory as this code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment