How to use vuex properly

How to use vuex properly

In this article, you will learn how to use vuex properly. First, it will let you know what vuex it is, then prompt you where and why should you use vuex as your storage management tool and finally how can you get started to use it for your own business.

At the end of this article, I will list some vuex learning resources which are helpful to me, you can go to learn if you think it is also useful to you.

What is vuex?

Vuex is a state management system for Vue applications. Note that it’s not come with Vue.js, you can use other state management systems like redux instead if you are more familiar with them, but vuex is tightly coupled with vue.js hence there are fewer compatible jobs to do.

Where and why should you use vuex?

Without vuex, how do you communicate normally between components?
Of course, you can use a property for passing data to child components from the parent component, emitting events for communicating to the parent component, you can even use event bus to communicate between any two components.

While your website is small, those ways work well, it’s unnecessary to introduce state management tool. If you insist, you will fall into the trap of overdesign, it’s inconvenient to jump code between files, your code reader will feel uncomfortable too.

But as the project becomes very large, the relationship between components becomes more and more complicated, using methods listed above will be painful and hard to maintain. That’s where vuex shows up.

How to get started?

Vuex has four basic parts:

  • The state, the data which controls the website;
  • The getters, the only way to access state;
  • The mutations, the only way to mutate state;
  • The actions, the possible way view layer modify state;

enter image description here

To get started using it, you need to follow the steps listed below.

Step1: Initialize the vuex store

import Vuex from 'vuex'
const store = new Vuex.Store({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions:{
  },
  modules: {
  }
})
export default store

Here we first import vuex from node_modules, then create a new instance of vuex, after that we use ES6 features to export it as a module. Now we need to import this store in main.js.

import Vue from 'vue'
import store from './store'
new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

Step2: Think carefully about what to put in the state management system

Almost all websites have login function, user login info needs to be shared from different components to do their functionality.in that case, I think store user information like user profile, user id, user token is a good practice.

state: {
  profile: Cookies.get('profile'),
  uid: Cookies.get('uid'),
  token: Cookies.get('token')
}

Step3: Write getters and mutations

Since a Vuex store’s state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue.

But remember that when you add new properties to an Object, replace the old state will not notify vue to re-render data. In that case, you are supposed to use Vue.set(obj, 'newProp', 123).

Besides that, getters and mutations are easy to write, here we just sync uid and token with the cookie. Here I use the browser’s cookie so that the user will not need to re-login after refreshing the page.

getters: {
  profile: state => state.profile,
  uid: state => state.uid,
  token: state => state.token
},
mutations: {
  SET_TOKEN: (state, token) => {
      state.token = token
      Cookies.set('token', token);
  },
  SET_PROFILE: (state, profile) => {
      state.profile = profile
      Cookies.set('profile', profile);
  },
  SET_UID: (state, uid) => {
      state.uid = uid
      Cookies.set('uid', uid);
  }
}

Step4: Write actions

last but not least, we need to write actions to call mutations, we can use Axios to asynchronously fetch data from the remote server.

actions: {
    login({ commit }, userInfo) {
        const { phone, smscode } = userInfo
        return new Promise((resolve, reject) => {
            axios.post({
                url: "/user/login",
                data: {
                    thirdtype: "phone",
                    thirdid: phone,
                    smscode: smscode
                }
            }).then(response => {
                const { data } = response
                commit('SET_UID', data.uid)
                commit('SET_TOKEN', data.token)
                commit('SET_PROFILE', data.profile)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },
}

Learning resources which may be helpful

  1. Vuex official documentation: Official documentation is always the first material I want to see.
  2. awesome-vue: A curated list of awesome things related to Vue.js.
  3. Vue element admin: A production-ready front-end solution for admin interfaces. It is based on vue and uses the UI Toolkit element-ui.

Conclusion

With this, you have learned the necessary concepts of vuex, you can now start exploring the advanced features of this state management system. Remember "Non sunt multiplicanda entia sine necessitate", if your project is not large enough to introduce a state management tool, then don’t overuse it.

Comments