Vue Simple Share State

by darkylmnx

HTML

<div id="app">
<btn-cmp text="i am a button"></btn-cmp>
<btn-cmp text="i am another button"></btn-cmp>
  <text-cmp></text-cmp>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

p {
  margin-bottom: 10px;
}

Vue

// create a reference
const store = {
	nb: 0
}

Vue.mixin({
	data() {
  	// here vue will merge each data object but will not create copies
    // it will pass by value or by reference
  	return {
    	store
    }
  }
})

Vue.component('btn-cmp', {
	props: {
  	text: {
    	required: true,
      type: String
    }
  },
	template: `<p><button @click="store.nb += 1"> {{ text }} </button></p>`
})

Vue.component('text-cmp', {
	template: `<p style="color: red">the shared counter is at {{ store.nb }}</p>`
})

new Vue({
  el: "#app"
})