1

I just started learning Vue and couldn't find an answer myself.

I have several arrays with data that will be loaded dynamically from the database. The objects inside them have an isLoaded property to identify the loading state.

The question is.

How can I change the value of isLoaded without passing the entire object to the mutation?

Like passing only the index and the name of an array.

Right now I do it like this:

    export default new Vuex.Store({
      state: {
        books: [
          {
            id: 1,
            title: 'Random',
            img: '',
            href: '/',
            isLoaded: false
          }
        ],
        games: [
          {
            id: 1,
            title: 'Random',
            img: '',
            href: '/',
            isLoaded: false
          }
        ]
      },
      getters: {
        books(state) {
          return state.books
        },
        games(state) {
          return state.games
        }
      },
      mutations: {
        updateLoadStatus(state, item) {
          item.isLoaded = true
        }
      }
    })

The isLoaded prop is needed in order to add the preloader class.

<div :class="{loading: !book.isLoaded}">
  <img :src="book.img" :alt="book.title" @load="updateLoadStatus(book)">
</div>

I have a lot more arrays than two, so I don't want do a separate mutation for each one.

1 Answer 1

1

This is how you define the mutation for it

mutations: {
        updateLoadStatus(state, payload) {
          state[payload.key][payload.index].isLoaded = payload.value;
        }
   }

and this is how you call it

this.$store.commit('updateLoadStatus', { key: 'books', index: 1, value:true}); // based on the object you pass as payload..the mutation will update the corresponding array item.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.