I'm currently in the process of developing a voting application with Vuex.
Within the app, there are buttons for each dog that users can vote for. I have successfully implemented functionality to update the vote count by clicking on the buttons:
store.js
export const store = new Vuex.Store({
state: {
dogs: [
{ id: 0, name: 'Dog1', vote: 0, percentage: 0 },
{ id: 1, name: 'Dog2', vote: 0, percentage: 0 },
{ id: 2, name: 'Dog3', vote: 0, percentage: 0 },
{ id: 3, name: 'Dog4', vote: 0, percentage: 0 },
{ id: 4, name: 'Dog5', vote: 0, percentage: 0 }
]
},
getters: {
dogs: state => {
return state.dogs;
},
},
mutations: {
vote: (state, payload) => {
const index = state.dogs.findIndex(dog => dog.id === payload);
state.dogs[index].vote++;
},
},
actions: {
voteAction(store, payload) {
store.commit('vote', payload)
},
}
})
Button.vue
<template>
<div v-for="(dog, index) in dogs" :key="index">
<button type="button" @click="vote(dog.id)">{{ dog.name }}</button>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import { mapMutations } from 'vuex';
export default {
computed: {
dogs() {
return this.$store.getters.dogs
}
},
methods: {
vote(id) {
this.$store.dispatch('voteAction', id);
},
}
}
</script>
My next goal is to calculate the percentage of votes for each dog and update all their percentages accordingly. This could potentially be achieved by:
- Obtaining the total number of votes
- Calculating the vote percentage for each dog
- Updating all the percentages
Although I am struggling to write this logic in the methods section of the store.js file. Additionally, I intend to receive the updated percentages in the Result.vue component.
<template>
Result.vue
<div v-for="(dog, index) in dogs" :key="index">
<div
class="progress-bar"
role="progressbar"
:style="{width: dog.percentage + '%'}"
aria-valuenow="dog.percentage"
aria-valuemin="0"
aria-valuemax="100"
>{{ dog.name }} {{ dog.percentage }}% ({{ dog.vote }} votes)</div>
</div>
</template>
<script>
export default {
computed: {
dogs() {
return this.$store.getters.dogs
},
},
}
</script>
How should I go about retrieving all the updated percentages from store.js to display in Result.vue?