Lesson 07-Vue3 State Management Library Vuex

Vuex Basic Usage

Installing Vuex

To use Vuex in your project, install it via npm if you’re using a Vue CLI project:

npm install vuex --save

Configuring the Vuex Store

Create a store directory in your project and initialize the Vuex store in index.js:

// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  getters: {}
});

State

The state is stored in the store’s state property, serving as a single source of truth accessible to all components.

// src/store/index.js
export default new Vuex.Store({
  state: {
    count: 0
  }
});

Access the state in components via this.$store.state.count.

State Mutations

State changes must be made through mutation functions, which receive state as the first parameter.

// src/store/index.js
export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

Call mutations in components using this.$store.commit('increment').

Asynchronous Operations (Actions)

Actions are similar to mutations but support asynchronous operations.

// src/store/index.js
export default new Vuex.Store({
  actions: {
    increment({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    }
  }
});

Dispatch actions in components using this.$store.dispatch('increment').

Computed Properties (Getters)

Getters are computed properties for the store, similar to Vue’s computed properties.

// src/store/index.js
export default new Vuex.Store({
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
});

Access getters in components via this.$store.getters.doubleCount.

Modular Store

For complex applications, split the store into modules.

// src/store/modules/user.js
const user = {
  state: {},
  mutations: {},
  actions: {},
  getters: {}
};

export default user;

// src/store/index.js
import user from './modules/user';

export default new Vuex.Store({
  modules: {
    user
  }
});

Plugin Integration

Vuex integrates with plugins like Vue Router or Axios, such as using Vuex state in navigation guards.

// src/router/index.js
import router from 'vue-router';
import store from '../store';

router.beforeEach((to, from, next) => {
  if (store.state.authenticated) {
    next();
  } else {
    next('/login');
  }
});

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here

Share your love