What is a Vuex

“Vuex is a state management pattern developed specifically for vue.js applications. It centrally manages the state of all components of an application, with rules that ensure that the state changes in a predictable way.”

So what is a state? In my understanding, it is the part of the vUE component’s data attributes that need to be shared with other VUE components, which is called state. In simple terms, these are attributes that need to be shared in data. So Vuex can be understood as a centralized management of properties (data) that need to be shared by all components and prescribes operations on these properties. Each time you operate on these attributes, follow the prescribed form, which ensures that the attributes “change in a predictable way.”

Vuex composition

The main concepts of Vuex are as follows:

  • Store

Represents a global reference to a Vuex object. The component accesses the State in the Vuex object via the Store (described below)

  • State

The state of a Vuex object, that is, the data it owns

  • Getter

A calculated property equivalent to a Store. Because just like evaluating properties, the return value of a Getter is cached according to its dependencies, and is only recalculated if its dependencies change. The specific usage scenarios are described below

  • Mutation

Defines operations that modify data in State. When a component uses the data in State, it cannot modify the data directly; the operations defined by Mutation need to be invoked to modify the data. This is also the Vuex definition of the specific implementation of the corresponding rules to make the data change

  • Action

The operations defined in Mutation can only perform synchronous operations, and the asynchronous operations in Vuex are performed in Action, which ultimately updates the data by calling the operations of Mutation

  • Module

A layer between Store and State for easy management of large projects. Store contains multiple Modules, and Modules contain State, Mutation, and Action

Using Vuex

Install Vuex

When we want to use Vuex in a vue project, we first need to install the Vuex dependency. Can be installed directly using NPM:

npm install vuex --save
// Add --save to indicate that the dependency is still needed after deployment.
Copy the code

Store, State, and Mutation

Create a store folder (or any other name) in your project’s source code folder, such as the SRC folder. Create a store.js file in the store folder to store the Vuex instance. Suppose our project is a reading class application that needs to maintain an array of book objects called books. If an application can add a new book, its basic store.js file would look like this:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    books: []},mutations: {
    // The first parameter of the method in all mutations must be the state variable, which is used to operate the state in state
    The second parameter is optional and is passed when the mutations method is invoked
    initBooks (state, books) {
      state.books = books
    },
    addNewBook (state, book) {
      state.books.unshift(book)
    }
  }
})

export default store
Copy the code

The scenario is as follows: In components (such as newbook.vue) that need to use common variables in stores, import the Store object first. Gets a reference to the Store object so that it can be acted upon later.

import store from '@/store/store'
Copy the code

Then use the Commit property of the Store instance in the component’s Methods to perform an operation on the data in the Store state:

methods: {
  onSubmit: function() {
    this.form.id = index++
    store.commit('addNewBook'.this.form)
  }
}
Copy the code

Updating data only by committing can feel cumbersome and unnecessary. Because wouldn’t it be easier to modify the data directly in the component? Commit by simply writing the action code that should have been written in the component to the store file, right? So why does Vuex still do that? Because the purpose of Vuex is “to ensure that the state changes in a predictable way with corresponding rules.” Components can only operate on the data in the methods specified in submit Mutation, ensuring predictability of state changes. If you allow components to change the state in state in place, the state can change in strange ways, and it’s hard to keep track of exactly where and what the data is changing.

In this way, the books array that should be maintained in newbook.vue (or its parent, just to give an example) is maintained in the Store. Every component that needs the books array must be fetched from the Store, and every operation on the books array must be committed. The method in mutations provides an interface to change the state in Store. With Vuex, we can finally get rid of the layers of trouble and confusion of passing on information.

The basic usage scenarios for Store, mutation, and state have been covered. Here are the rest.

Action

You can only do synchronous operations in mutation, so what if asynchronous operations are needed? In the example above, the reading application assumes that the application needs to get all the books in the database from the server at startup. This operation is time-consuming compared to other basic operations. In order to ensure smooth application, the book data should be obtained asynchronously. Because this operation updates the Books array, Vuex needs to be notified to update the data by way of a commit, but mutation can only be synchronized. Vuex provides a way to perform asynchronous operations, called actions. Actions are defined in the same way as those in mutation, except that they are asynchronous and cannot directly change the state in state, which is ultimately changed by committing. Add the following store.js file after Action:

import Vue from 'vue'
import Vuex from 'vuex'
// Use AXIos as the HTTP service module
import axios from 'axios'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    books: []},mutations: {
    // The first parameter of the method in all mutations must be the state variable, which is used to operate the state in state
    The second parameter is optional and is passed when the mutations method is invoked
    initBooks (state, books) {
      state.books = books
    },
    addNewBook (state, book) {
      state.books.unshift(book)
    }
  },
  actions: {
    //{commit} {commit} {commit}
    fetchData ({ commit }) {
      axios.get('http://127.0.0.1:8081/api/books')
          .then(function (response) {            
            commit('initBooks', response.data)
          })
          .catch(function (error) {
            console.log(error)
          })
    },
    // Book is the additional argument passed when the operation is called
    addItem ({ commit }, book) {
      return axios.post('http://127.0.0.1:8081/api/add', book)
              .then(function (response) {
                if(! response || response.status ! = =200 || response.data.err) {
                  return true
                } else {
                  commit('addNewBook', book)
                  return false}}); }}})export default store
Copy the code

The following scenarios are used: Instead of committing a method, an Action method is called in a component using the “dispatch” method:

if (store.state.books.length === 0) {
  store.dispatch('fetchData')}Copy the code

Of course, you can also pass parameters to the distribution:

methods: {
  onSubmit: function() {
    this.form.id = index++
    this.form.bookname = "" " + this.form.bookname + "" "
    store.dispatch('addItem'.this.form)
        .then((err) = > {
          if(! err) {this.$message({
              message: 'Added successfully! '.type: 'success'})}else {
            this.$message.error('Add failed! ')}})}}Copy the code

It can also be distributed by means of an object:

const store = new Vuex.Store({
  state: {
    books: []},getters: {
    doneBooks: state= > {
      return state.books.filter(book= > book.done)
    }
  }
})
Copy the code

Getters are exposed as store.getters objects, and these values are accessed as properties:

store.getters.doneBooks
Copy the code

Finally, when should Vuex be used

Vuex’s official documentation reminds us that while Vuex can help us manage shared state, it also comes with more concepts and frameworks. Simply put, you don’t need to use Vuex if your project is small and its status is not complex enough to be managed using Vuex.

Reprinted from: blog.csdn.net/shujh_sysu/…