Answer the question
In order to leave comments, you need to log in
How to work with Vuex in this case?
Started learning Vuex and got a little confused. The bottom line is that there is an array of objects that is in "state", there is also a variable, it is also in "state", you need to iterate through the array, find out how many variables there are with the value "true" and write to the variable that lies in state.
This is what the store looks like:
let store = new Vuex.Store({
actions:{
},
mutations:{
},
state:{
favourites: 0,
blocks:[
{
favourite: false,
},
{
favourite: false,
},
{
favourite: true,
},
{
favourite: false,
},
]
},
getters:{
}
});
let favourites = function(){
let i = 0;
blocks.forEach(function (el) {
if (el.favourite === true){
i++;
}
return i;
})
};
favourites: state => {
return state.blocks.filter(block => block.favourite).length;
}
import { mapState } from 'vuex';
export default {
computed: mapState(['favourites','compare','basket'])
}
computed:{
...mapState(['compare','basket']),
...mapGetters(['favourites'])
}
Answer the question
In order to leave comments, you need to log in
The question of the magic of the filter method remains open.
block => block.favourite
, which takes a block as input and returns either true or false as output. Now look at how the filter method works (iterates over all elements, calling the callback, and leaves only those elements that returned true in the callback). Actually after that we consider how many elements filtered by such a condition are left ( .length
it does), there is no magic in this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question