V
V
VegasChickiChicki2019-07-18 06:17:23
JavaScript
VegasChickiChicki, 2019-07-18 06:17:23

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:{

  }
});

I can't figure out how to filter the "blocks" array, I think you can use ForEach, something like:
let favourites = function(){
let i = 0;
    blocks.forEach(function (el) {
        if (el.favourite === true){
            i++;
        }
        return i;
    })
};

And I can't figure out how to write this into the "favourites" variable later. Perhaps it is worth creating some kind of method in mutations ... Please help, thank you.
UPD.
I realized that I need to add a method to getters.
I figured out what the filter function should be:
favourites: state => {
          return state.blocks.filter(block => block.favourite).length;
      }

But there were still questions why it works, although I did not specify any filtering conditions, but it returns an object from fields that are only true, we take its length accordingly.
And another question, how to access both the computed field and the getters field in the template at the same time?
now the call is:
import { mapState } from 'vuex';

  export default {
    computed: mapState(['favourites','compare','basket'])
  }

UPD2.
I learned what object syntax is, I used the following method to combine objects:
computed:{
          ...mapState(['compare','basket']),
          ...mapGetters(['favourites'])
      }

The question of the magic of the filter method remains open.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Arutyunov, 2019-07-18
@VegasChickiChicki

The question of the magic of the filter method remains open.

You have an arrow function: 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 ( .lengthit does), there is no magic in this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question