1
I have the following code below using Vue.js and Vuex. This code increments and decreases value as a counter. I would like to know what the method refers to count
inside computed in Vue instance. I know it returns the state of the variable Count of state
. But why does the method name have to be the variable name? If I change the method name the code does not work.
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
incrementa: state => state.count++,
decrementa: state => state.count--
}
})
new Vue({
el: '#app',
computed: {
count() { // Dúvida -> ao que se refere count
return store.state.count
}
},
methods: {
incrementa() {
store.commit('incrementa')
},
decrementa() {
store.commit('decrementa')
}
}
})
span{padding: 0 15px;}
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<p>
<button @click="incrementa">+</button>
<span>{{ count }}</span>
<button @click="decrementa">-</button>
</p>
</div>
All right, you came up with another method (Testing) inside computed that returns the store with the state of the variable Count and this method does the same as the method Count, right. Only doubt persists, if you change the name of the method
count()
error, this you would like to know pq? You said in your reply "In this case, the method name inside the computed does not need to be the same variable name", tries to rename Count() to see if there is no error.– LeAndrade
Dude if you change the computed Count() you have to change the HTML to the name you changed, did you change it? computed is like a data() variable, so it has to change in HTML as well, the name of HTML and computed must be exactly the same.
– guastallaigor
Exact man, it was this even though I wasn’t getting it. I switched on computed but not HTML. Thanks plea help!
– LeAndrade