A Vue.js project
This repo contains some simplest case examples on Vuex for learning purpose. I also add my daily logs here, about what I have learned so far to keep track of my progress.
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run buildFor detailed explanation on how things work, consult the docs for vue-loader.
- Learned about what Vuex is and why we will want to use it.
- Vuex allows us to manage our app state within Vue JS very easily.
- Also, created a simple vue template using vue-cli.
- Created a simple vue app and passing data to child components using
props. - This app will be used to experiment with Vuex.
-
Installed
vuexto this project.npm install vuex --save
-
Worked on setting up a central store using
vuex.
- Learned how we can access central
vuexstore in our child components without using anyprops. - By providing the
storeoption to the root instance, the store will be injected into all child components of the root and will be available on them asthis.$store.
-
Learned about use-cases for getters in
vuex. -
If more than one component needs to make use of a computed property based on store state, we can put that as "getters" in the store. It acts like a computed property for store.
-
Getters receives the state as their 1st argument.
const store = new Vuex.Store({ state: { todos: [{ id: 1, text: '...', done: true }, { id: 2, text: '...', done: false }] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done); } } });
-
The getters are exposed on the
store.gettersobject:this.$store.getters.doneTodos; // -> [{ id: 1, text: '...', done: true }]
- Learned about mutations in
vuex. - Used mainly for direct modification of state in
vuex. - Mutations must be synchronous and shouldn't return a value.
- They can be used directly by running
this.$store.commit('mutationName', payload).
- Learned about actions in
vuex. - The most obvious use of
actionsis for performing asynchronous operations, where amutationis called after the operation completes. - Note that mutations themselves cannot be asynchronous.
- Today learned about mapping actions & getters using
mapGetters&mapActionshelpers. - The
mapGettershelper simply maps store getters to local computed properties. - We can dispatch actions in components with
this.$store.dispatch('xxx'), or use themapActionshelper which maps component methods tostore.dispatchcalls (requires root store injection).import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // map `this.increment()` to `this.$store.dispatch('increment')` // `mapActions` also supports payloads: 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')` }) } }