Vuex: a powerful state management model

About the author: Java up master who has been practicing for two and a half years
Personal homepage: Programmer Laocha
ps: Likes are free, but they can make the blog author happy for a long time
Column series: Java full stack, computer series (updating rapidly)
Motto: The best time to plant a tree was ten years ago, the second best time is now
Move your little hands and click follow to avoid getting lost. Thank you guys for one click and three links.

Directory

  • Course name: Vuex
    • Content/function: knowledge points/design/experiments/assignments/exercises
    • Learn: Vuex
  • Vuex: a powerful state management model
  • What is Vuex?
  • The role and advantages of Vuex
  • When should I use Vuex?
  • How to use Vuex?
    • Installation and configuration
    • Define states and mutations
    • Using state and mutations in components
  • Summarize

Course name: Vuex

Content/function: knowledge points/design/experiments/assignments/exercises

Learn: Vuex

Vuex: a powerful state management model

Address: https://vuex.vuejs.org/zh/

What is Vuex?

Vuex is a state management pattern + library developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.

This state self-management application consists of the following parts:

  • State, the data source that drives the application;
  • Views, which declaratively map state to views;
  • Actions that respond to state changes caused by user input on a view.

Here is a simple illustration representing the idea of “one-way data flow”:

However, the simplicity of one-way data flow is easily broken when our application encounters multiple components sharing state:

  • Multiple views depend on the same state.
  • Actions from different views require changing the same state.

Regarding question 1, the method of passing parameters will be very cumbersome for multi-layer nested components, and it is powerless for state transfer between sibling components. For question two, we often use parent-child components to directly reference or use events to change and synchronize multiple copies of the state. These patterns are very fragile and often lead to unmaintainable code.

Therefore, why don’t we extract the shared state of the component and manage it in a global singleton mode? In this mode, our component tree forms a huge “view”, and any component can obtain status or trigger behavior no matter where it is in the tree!

By defining and isolating the various concepts in state management and maintaining the independence between views and state by enforcing rules, our code will become more structured and maintainable.

This is the basic idea behind Vuex, borrowed from Flux, Redux and The Elm Architecture. Unlike other patterns, Vuex is a state management library specifically designed for Vue.js to take advantage of Vue.js’s fine-grained data response mechanism for efficient state updates.

If you want to learn Vuex interactively, check out this Vuex course on Scrimba, which mixes a screen recording with a code testing ground that you can pause and try at any time.

The functions and advantages of Vuex

In large Vue.js applications, state management between components is a complex task. As the application scale expands, state transfer and synchronization become difficult, and it can also easily lead to code redundancy and difficulty in maintenance. The emergence of Vuex is to solve these problems.

  • Centralized storage: Vuex stores all the state of the application in a single state tree, called a “store”. This allows us to centrally manage state and ensure that all components can access and modify the same state data.
  • State sharing: By defining a store, different components can easily share state and stay synchronized in real time. In this way, we can better track state changes and avoid the cumbersome operations of traditional cross-component communication.
  • Better debugging tools: Vuex provides powerful debugging tools that can help us track state changes, record the trajectory of each mutation, and provide better error prompts during the development process.

When should I use Vuex?

Vuex can help us manage shared state and comes with more concepts and frameworks. This requires weighing short- and long-term benefits.

If you don’t plan to develop a large single-page application, using Vuex may be cumbersome and redundant. It’s true – if your app is simple enough, you’re probably better off not using Vuex. A simple store pattern is all you need. However, if you need to build a medium to large single-page application, you will most likely be thinking about how to better manage state outside of the component, and Vuex will be a natural choice.

How to use Vuex?

Next, let’s take a closer look at how to use Vuex to manage the state of a Vue.js application. Here are the specific steps:

Installation and configuration

First, make sure your Vue.js project has Vuex installed. Execute the following command in the project root directory:

npm install vuex --save

Then, import and configure Vuex in your Vue.js application entry file (usually main.js):

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({<!-- -->
  // Define your state and mutations here
})

new Vue({<!-- -->
  store,
  // ...other Vue instance options
}).$mount('#app')

Define states and mutations

In the above configuration code, we need to define our state and mutations in the parameters of new Vuex.Store(). State refers to the data we need to share and manage, and mutations are methods used to modify state.

const store = new Vuex.Store({<!-- -->
  state: {<!-- -->
    count: 0
  },
  mutations: {<!-- -->
    increment(state) {<!-- -->
      state.count++
    },
    decrement(state) {<!-- -->
      state.count--
    }
  }
})

In the above example, we define a state named count and provide two mutations: increment and decrement. These mutations are used to increase and decrease the value of the count state respectively.

Using state and mutations in components

Now that we have defined states and mutations, we can use them in our components. In the Vue.js component, we can access the state and mutations in the store through this.$store.

<template>
  <div>
    <p>Count: {<!-- -->{ count }}</p>
    <button @click="increment"> + 1</button>
    <button @click="decrement">-1</button>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment')
    },
    decrement() {
      this.$store.commit('decrement')
    }
  }
}
</script>

In the above example, we use the calculated property count to obtain the value of the count status and display it in the template. At the same time, we also defined two methods increment and decrement, which are used to call increment and decrement mutations respectively. Modify status.

Summary

Through the above steps, we successfully used Vuex to manage the state of the Vue.js application. Vuex provides a powerful way to organize and manage state, allowing us to better handle complex application logic and data flows. I hope this article will help you understand and use Vuex!

Previous columns
Java full stack development
Data structures and algorithms
Principles of computer composition
Operating system
Database system
Internet of Things control principles and technology