Tuesday, 11 May 2021

Vuex Actions && Commits && MappedGetters all in 1

 https://vuex.vuejs.org/guide/actions.html#dispatching-actions


const store = new Vuex.Store({

  state: {

    count: 0

  },

// synchoronus, save to local stroage state.count

  mutations: {

    increment (state) {

      state.count++

    }

  },

// asynchoronus call mutation // commits calls mutation(store.commit)

  actions: {

    increment ({ commit }) {

     commit('increment')

    }

  }

})


// Component

this.$store.dispatch('increment')


--------------------------------------------------------------

store folder /

const store = new Vuex.Store({

  state: {

    todos: [

      { id: 1, text: '...', done: true },

      { id: 2, text: '...', done: false }

    ]

  },

// Get from cache

  getters: {

    doneTodos: state => {

      return state.todos.filter(todo => todo.done)

    }

  }

})


Vue component (creates computed variable "doneTodoScount"

computed: {

  doneTodosCount () {

    return this.$store.getters.doneTodosCount

  }

}



This is equivalent to 

https://vuex.vuejs.org/guide/getters.html#method-style-access

import { mapGetters } from 'vuex'


export default {

  // ...

  computed: {

    // mix the getters into computed with object spread operator

    ...mapGetters([

      'doneTodosCount',

      'anotherGetter',

      // ...

    ])

  }

}





No comments:

Post a Comment