Categories
JavaScript Vue

Adding Mutations to a Vuex Store

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

With Vuex, we can store our Vue app’s state in a central location.

In this article, we’ll look at how to add mutations to a Vuex store so that we can update the store’s state and propagate the change to components that uses the store.

Adding Mutations

We can add a mutation by putting in a function that changes the state by taking it from the parameter and then mutating it.

For example, we can write the following code:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

Then we can run the mutation function by running:

store.commit('increase')

Then state.count should go up by 1.

We can’t run mutation functions directly.

Commit with Payload

If we want to pass our own argument to it, we can add it after the state parameter, so we write:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, num) {  
      state.count += num;  
    }  
  }  
});

Then we can commit the mutation by writing:

store.commit('increase', 10)

Then state.count should go up by 10.

The second parameter is usually an object, so we can access property values by writing:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  }  
});

Then we can commit the mutation by writing:

store.commit('increase', {  
  amount: 10  
})

Any state changes will be observed by components automatically if they access the store from within it.

Vue’s reactivity rules like initializing initial state and using Vue.set to update objects, etc. all applies to Vuex stores.

We can replace strings for mutation names with constants by assigning them to constants.

For example, we can change the example we have above to:

const INCREASE = "increase";

const store = new Vuex.Store({  
  state: {  
    count: 1  
  },  
  mutations: {  
    [INCREASE](state, payload) {  
      state.count += payload.amount;  
    }  
  }  
});

store.commit(INCREASE, { amount: 10 });

JavaScript since ES6 can have dynamic property names, so we can take advantage of that to replace names with constants.

Mutations Must Be Synchronous

Mutations must be synchronous because they’re untrackable since asynchronous code can be called at any time rather than line by line like synchronous code is.

Committing Mutations in Components

We can either use this.$store.commit to commit mutations or we can use Vuex’s helper methods to do so.

this.$store.commit

For example, we can use this.$store.commit as follows:

index.js :

const INCREASE = "increase";const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    [INCREASE](state, payload) {  
      state.count += payload.amount;  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  computed: Vuex.mapState(["count"]),  
  methods: {  
    increase(amount) {  
      this.$store.commit(INCREASE, { amount });  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increase(10)">Increase</button>  
      <p>{{count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we have the increase method as follows:

increase(amount) {  
  this.$store.commit(INCREASE, { amount });  
}

This is called by our template when we click the Increase button.

this.$store.commit(INCREASE, { amount }); will increase state.count by the amount we pass in, which is 10.

Then we get the state back by using mapState so we can display it in our template.

When we click Increase, we get 10, 20, 30, etc.

mapMutations

We can use mapMutations to map mutations to methods in our component as follows:

index.js :

const INCREASE = "increase";

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    [INCREASE](state, payload) {  
      state.count += payload.amount;  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  computed: Vuex.mapState(["count"]),  
  methods: {  
    ...Vuex.mapMutations([INCREASE])  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increase({amount: 10})">Increase</button>  
      <p>{{count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, mapMutations maps the mutation methods to the component methods.

So:

...Vuex.mapMutations([INCREASE])

maps the increase method adds an increase method to the component which calls this.$store.commit(INCREASE) .

INCREASE is the string 'increase' that we have in the first line.

In the template, we just called increase({amount: 10}) when the Increase button is clicked to update state.count in the store.

Conclusion

We add mutations to our Vuex store to update the state of our store.

To do this, we add methods under the mutations object.

Then we can call this.$store.commit or use mapMutations to map mutation methods in the store to component methods.

Mutations must be synchronous since they need to be trackable.

Categories
JavaScript Vue

Adding Actions to a Vuex Store

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

With Vuex, we can store our Vue app’s state in a central location.

In this article, we’ll look at how to add actions to our Vuex store to change the store’s state.

What are Actions?

Actions are similar to mutations, but they commit mutations instead of mutating the state. Actions can also commit asynchronous operations unlike mutations.

For example, we can add a simple action as follows:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  },  
  actions: {  
    increase(context) {  
      context.commit("increase");  
    }  
  }  
});

An action takes a context object, which we can use to call commit to commit a mutation.

Dispatching Actions

We can dispatch actions by calling store.dispatch('increase') .

It’s much more useful than commit mutations directly because we can run asynchronous operations with it.

For example, we can dispatch an action as follows in Vue app:

index.js :

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increaseAsync({ commit }, payload) {  
      setTimeout(() => {  
        commit("increase", payload);  
      }, 1000);  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  methods: {  
    ...Vuex.mapActions(["increaseAsync"])  
  },  
  computed: {  
    ...Vuex.mapState(["count"])  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src=[https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increaseAsync({amount: 10})">Increase</button>  
      <p>{{count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we have the action increaseAsync with the following code:

increaseAsync({ commit }, payload) {  
  setTimeout(() => {  
    commit("increase", payload);  
  }, 1000);  
}

In the action method, we commit the increase mutation with a payload object that we pass in when we dispatch the action.

In the Vue instance, we have:

methods: {  
    ...Vuex.mapActions(["increaseAsync"])  
},  
computed: {  
  ...Vuex.mapState(["count"])  
}

which maps the actions in the store by calling mapActions , and added computed properties by mapping them from the store by using mapState so we get a count property which is computed from state.count as a computed property.

Then in the template, we call increaseAsync when we press the Increase button to update state.count after 1 second.

Finally, we should see the number updated since we mapped the state from the store.

Composing Actions

We can chain actions that return promises.

For example, we can create an action to update 2 counts as follows:

index.js :

const store = new Vuex.Store({  
  state: {  
    count1: 0,  
    count2: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count1 += payload.amount;  
    },  
    decrease(state, payload) {  
      state.count2 -= payload.amount;  
    }  
  },  
  actions: {  
    async increaseAsync({ commit }, payload) {  
      return Promise.resolve(commit("increase", payload));  
    },  
    async decreaseAsync({ commit }, payload) {  
      return Promise.resolve(commit("decrease", payload));  
    },  
    async updateCounts({ dispatch }, payload) {  
      await dispatch("increaseAsync", payload);  
      await dispatch("decreaseAsync", payload);  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  methods: {  
    ...Vuex.mapActions(["updateCounts"])  
  },  
  computed: {  
    ...Vuex.mapState(["count1", "count2"])  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="updateCounts({amount: 10})">Update Counts</button>  
      <p>Count 1: {{count1}}</p>  
      <p>Count 2: {{count2}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we have the updateCounts action switch calls dispatch with the increaseAsync action and payload . Then it calls dispatch with the decreaseAsync action and payload .

increaseAsync commits the increase mutation, and decreaseAsync commis the decrease mutation.

Since they all have Promise.resolve , they’re all async.

Then we include the updateCounts action from the store in our Vue instance with mapActions . And we also include the count1 and count2 states with mapState .

Then when we click the Update Counts button, we call updateCounts , and then count1 and count2 are updated as we click the button. count1 should increase by 10 each time and count2 should decrease by 10 each time we click it.

Conclusion

We can use actions to commit one or more mutations or dispatch other actions.

It’s handy for grouping store operations together and running asynchronous code since mutations are always synchronous.

We can use mapActions to include them in our components.

Actions are dispatched by calling dispatch , while mutations are committed with the commit method.

Categories
JavaScript Vue

Adding Modules to a Vuex Store

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

With Vuex, we can store our Vue app’s state in a central location.

In this article, we’ll look at how to add modules to separate a Vuex store into smaller parts.

Dividing a Store into Modules

Vuex uses a single state tree. This means the states are located in one big object. This will be bloated is our app grows big.

To make a Vuex store easier to scale, it can be separated into modules. Each module can have its own state, mutations, getters, and actions.

The state parameter in mutations and getters are the module’s local state.

By default, all actions, mutations, and getters inside modules are registered under a global namespace. This allows multiple modules to react to the same mutation or action type.

We can divide our store into module as in the following example:

index.js :

const moduleA = {  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const moduleB = {  
  state: {  
    count: 1  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const store = new Vuex.Store({  
  modules: {  
    a: moduleA,  
    b: moduleB  
  }  
});

console.log(store.state.a.count);  
console.log(store.state.b.count);

Then in the console.log output, we should see 0 and 1 since moduleA ‘s initial count state is 0 and moduleB ‘s initial count state is 1.

To make each module self-contained, we have to namespace it by setting the namespaced option to true .

We can namespace a module and then call dispatch on actions after namespacing the modules as follows:

index.js :

const moduleA = {  
  namespaced: true,  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const moduleB = {  
  namespaced: true,  
  state: {  
    count: 1  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const store = new Vuex.Store({  
  modules: {  
    a: moduleA,  
    b: moduleB  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  computed: {  
    ...Vuex.mapState({  
      a: state => state.a,  
      b: state => state.b  
    })  
  },  
  methods: {  
    increaseA(payload) {  
      this.$store.dispatch("a/increase", payload);  
    },  
    increaseB(payload) {  
      this.$store.dispatch("b/increase", payload);  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increaseA({amount: 10})">Increase</button>  
      <button @click="increaseB({amount: 10})">Increase</button>  
      <p>A Count: {{a.count}}</p>  
      <p>B Count: {{b.count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we have namespaced: true set in each module, and then we added 2 methods to our Vue instance to dispatch the namespaced actions:

increaseA(payload) {  
  this.$store.dispatch("a/increase", payload);  
}

and:

increaseB(payload) {  
  this.$store.dispatch("b/increase", payload);  
}

Since we have namespaced set to true , we have to dispatch the actions by passing in “a/increase” and “b/increase” to dispatch .

Then once we clicked the buttons, our methods are called to dispatch the actions and the numbers will increase.

Register Global Action in Namespaced Modules

We can also register global actions in namespaced modules, by setting the root option to true and place the action definition in the function handler.

To do register a global action, we can write something like the following code:

index.js :

const moduleA = {  
  namespaced: true,  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const moduleB = {  
  namespaced: true,  
  state: {  
    count: 1  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const rootModule = {  
  actions: {  
    increaseAll: {  
      root: true,  
      handler(namespacedContext, payload) {  
        namespacedContext.commit("a/increase", payload);  
        namespacedContext.commit("b/increase", payload);  
      }  
    }  
  }  
};

const store = new Vuex.Store({  
  modules: {  
    a: moduleA,  
    b: moduleB,  
    root: rootModule  
  }  
});

new Vue({  
  el: "#app",  
  store,  
  computed: {  
    ...Vuex.mapState({  
      a: state => state.a,  
      b: state => state.b  
    })  
  },  
  methods: {  
    ...Vuex.mapActions(["increaseAll"])  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increaseAll({amount: 10})">Increase All</button>  
      <p>A Count: {{a.count}}</p>  
      <p>B Count: {{b.count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we added the rootModule which has the global action as follows:

const rootModule = {  
  actions: {  
    increaseAll: {  
      root: true,  
      handler(namespacedContext, payload) {  
        namespacedContext.commit("a/increase", payload);  
        namespacedContext.commit("b/increase", payload);  
      }  
    }  
  }  
};

A global action has the root option set to true and a handler method which is used to dispatch actions from any module.

Then in the Vue instance, we have:

methods: {  
  ...Vuex.mapActions(["increaseAll"])  
}

to map the increaseAll action to a method in the Vue instance.

Then in the template, we have:

<button @click="increaseAll({amount: 10})">Increase All</button>

to call the increaseAll method returned from the mapActions method when the button is clicked.

Then we should both numbers increasing since we mapped both module’s state to the Vue instance’s data.

Dynamic Module Registration

We can also register a module dynamically by using the store.registerModule method as follows:

index.js :

const moduleA = {  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state, payload) {  
      state.count += payload.amount;  
    }  
  },  
  actions: {  
    increase({ commit }, payload) {  
      commit("increase", payload);  
    }  
  }  
};

const store = new Vuex.Store({});

store.registerModule("a", moduleA);

new Vue({  
  el: "#app",  
  store,  
  computed: {  
    ...Vuex.mapState({  
      a: state => state.a  
    })  
  },  
  methods: {  
    ...Vuex.mapActions(["increase"])  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <button @click="increase({amount: 10})">Increase</button>  
      <p>A Count: {{a.count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

The store.registerModule takes a string for the module name, and then an object for the module itself.

Then we can call the helpers to map getters to computed properties and actions/mutations to methods. In the code above, we have the increase action mapped to a method.

Then we can call it in our template as usual.

Conclusion

If our Vuex store is big, we can divide it into modules.

We can register modules when we create the store or dynamically with registerModule .

Then we can map actions/mutations by their name as usual, and we can map the state by accessing state.a.count , where a is the module name, and count is the state name. Replace it with our own module and state names if the code is different.

We can also namespace the modules. Then we dispatch the actions starting with the module name and a slash instead of just the name.

Categories
JavaScript Vue

Add Simple State Management with Vuex

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

With Vuex, we can store our Vue app’s state in a central location.

In this article, we’ll look at how to add Vuex to our app and add a simple store.

What is Vuex?

Vuex is for storing states that are needed by multiple components in one central location.

https://thewebdev.info/wp-content/uploads/2020/06/vuex.png

It lets us get and set shared state and propagate any changes made to the shared state automatically to all components.

In the workflow diagram above, we can see that Vuex mutations are committed by our code when we get something from the back end API.

The mutation will update the state with the back end API data and the state will be updated in our Vue components.

We can also dispatch mutations from Vue components to change the Vuex store state the change will be propagated to all components that have access to the store.

Getting Started

We can include Vuex with a script tag in our HTML code:

<script src="https://unpkg.com/vuex"></script>

Then we can create a simple store by using the Vuex.Store as follows:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

The code above is a store which stores the state count .

Then we can commit the increase mutation by running:

store.commit("increase");

Then we can get the state after the mutation is done by running:

console.log(store.state.count);

store.state.count is the count state from the Vuex store. Then we should see 1 logged.

Getting Vuex State into Vue Components

We can get the state into our store by adding a computed property.

Therefore, to add the state into our store, we can write the following:

index.js :

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

new Vue({  
  el: "#app",  
  computed: {  
    count() {  
      return store.state.count;  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <p>{{count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

Then we should see 0 displayed since count is 0 initially in the store .

Then whenever store.state.count updates, the computed property will be updated and the view will update with the new value.

A more convenient way to inject the store into all child components is to add the store in the root component as follows:

index.js :

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <p>{{$store.state.count}}</p>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

Then it’ll be available to all child components and we don’t have to worry about add computed properties for every value.

It works with child component without much changes:

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

Vue.component("counter", {  
  template: `<div>{{ count }}</div>`,  
  computed: {  
    count() {  
      return this.$store.state.count;  
    }  
  }  
});

new Vue({  
  el: "#app",  
  store  
});

this.$store is available to the counter component just by including it in the root Vue component.

The mapState Helper

To avoid adding a new computed property for every state that’s in the store, we can use the mapState helper to add it. For example, we can write the following code to do that:

index.js :

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

Vue.component("counter", {  
  data() {  
    return {  
      localCount: 1  
    };  
  },  
  template: `  
    <div>  
      <div>{{ count }}</div>  
      <div>{{ countAlias }}</div>  
      <div>{{ countPlusLocal }}</div>  
    </div>  
  `,  
  computed: Vuex.mapState({  
    count: state => state.count,  
    countAlias: "count",  
    countPlusLocal(state) {  
      return state.count + this.localCount;  
    }  
  })  
});

new Vue({  
  el: "#app",  
  store  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vuex"></script>  
  </head>  
  <body>  
    <div id="app">  
      <counter></counter>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

Then we see:

001

Because we called mapState as follows:

computed: Vuex.mapState({  
  count: state => state.count,  
  countAlias: "count",  
  countPlusLocal(state) {  
    return state.count + this.localCount;  
  }  
})

We have:

count: state => state.count,

which gets the count state from the store and returns it. The count is 0 so we get 0.

Then we have:

countAlias: "count"

which is a shorthand for:

count: state => state.count

And finally, we have:

countPlusLocal(state) {  
  return state.count + this.localCount;  
}

which adds state.count from the store to this.localCount , which we set to 1.

Object Spread Operator

We can combine local computed properties with mapState by applying the spread operator to mapState as follows:

index.js :

const store = new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increase(state) {  
      state.count++;  
    }  
  }  
});

Vue.component("counter", {  
  data() {  
    return {  
      localCount: 1  
    };  
  },  
  template: `  
    <div>  
      <div>{{ count }}</div>  
      <div>{{ foo }}</div>        
    </div>  
  `,  
  computed: {  
    foo() {  
      return 2;  
    },  
    ...Vuex.mapState({  
      count: "count"  
    })  
  }  
});

new Vue({  
  el: "#app",  
  store  
});

Then we get:

02

displayed since foo always returns 2.

Components Can Still Have Local State

Components can still have their own local state, so we don’t have to put everything in the Vuex store.

Conclusion

We can add a Vuex store to our app to store the states of our app that are shared by multiple components.

To make getting state easy, we can include the store in the root Vue component.

Then we call the mapState helper to get the states we want in any component.

We can also combine it with the local states with the spread operator in the computed object.

Categories
JavaScript Vue

Using a For Loop with Vuejs

We can render lists by using a for loop with Vuejs.

The for loop equivalent in Vuejs is the v-for directive.

To use it, we can write;

<ul id="example">
  <li v-for="item in items" :key="item.name ">
    {{ item.name }}
  </li>
</ul>

and:

const example = new Vue({
  el: '#example',
  data: {
    items: [
      { name: 'Foo' },
      { name: 'Bar' }
    ]
  }
})

We have an items array with the list items to render

Then we use v-for with the items array to render them items.

We need the key prop with a unique value for each entry for Vuejs to identify the entries properly.

We can also add the index by changing our v-for for loop.

For instance, we can write:

<ul id="example">
  <li v-for="(item, index) in items">
    {{ index }} - {{ item.name }}
  </li>
</ul>

and:

const example = new Vue({
  el: '#example',
  data: {
    parentMessage: 'Parent',
    items: [
      { name: 'Foo' },
      { name: 'Bar' }
    ]
  }
})

index has the index of the array.

We can also loop through objects.

For instance, we can write:

<ul id="v-for-object">
  <li v-for="value in object">
    {{ value }}
  </li>
</ul>

and

new Vue({
  el: '#v-for-object',
  data: {
    object: {
      name: 'james'.
      age: 20,
      gender: 'male'
    }
  }
})

We loop through the keys of the object in our Vuejs app with the same for loop.

value has the property value.

We can also add the property name and index to the loop.

For instance, we can write:

<div v-for="(value, name) in object">
  {{ name }}: {{ value }}
</div>

value is the property value and name is the property name.

We can also add the index to our Vuejs for loop by writing:

<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

We can create a Vuejs for loop that display numbers by writing a number after the in instead of an array or object.

For instance, we can write:

<div>
  <span v-for="n in 100">{{ n }} </span>
</div>

We can v-for with a `template component to render multiple items.

For instance, we can write:

<ul>
  <template v-for="item in items">
    <li>{{ item.msg }}</li>
    <li><hr /></li>
  </template>
</ul>

to render multiple items in each iteration of the v-for Vuejs for loop.

The Vuejs equivalent of a for loop is the v-for directive.

We can use it to render objects and array entries on the screen.

Also, we can use it to loop through a range of numbers and display them.