The project I'm working on can be found here. It is a simple one, but for the purpose of learning, I divided it into index and four js files (parent, child, root, and store). My challenge lies in figuring out how to call the increment and decrement root methods in the child component without resorting to commits within the elements or engaging in poor practices like using props or this.$root
inside the components.
Here is the code breakdown:
index.html:
<div id="app">
<parent></parent>
</div>
root.js:
let vm = new Vue({
el: '#app',
store,
methods:{
increment(){
store.commit('incrementar')
},
decrement(){
store.commit('decrementar')
}
}
})
store.js:
const store = new Vuex.Store({
state:{
numero: 11
},
mutations:{
incrementar(state){
state.numero++
},
decrementar(state){
state.numero--
}
}
})
parent.js:
Vue.component('parent',{
template:
`
<div>
<h1>Number: {{$store.state.number}}</h1>
<child></child>
</div>
`
})
child.js:
Vue.component('child',{
template:
`
<div>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<h1>Number: {{number}}</h1>
</div>
`,
computed: {
number() {
return store.state.number
}
}
I have read that events should be used, but I am unsure about implementing them with the buttons. Keep in mind that I am relatively new to JavaScript, Vue, and Vuex.