What is vuex?

Vuex is a tool provided by VUE to manage public data independently of the component system. It uses centralized storage to manage the status of all application components and to solve the communication between multiple components

Key points:

  1. Vue official collocation, exclusive use (similar to: VUe-router), has a special debugging tool
  2. The centralizedManage data state scheme (simpler operation)Data () {return {data, status}}
  3. Data changes are predictable (responsive)

Key points:

Vuex is vUE's official tool for managing public data, independent of component architecture

Usage Scenarios:

Large projects require complex value transfer between components


The relationship diagram of state, Actions and mutations in VUEX

How vuEX was used in the project

  1. In the old project.Install the VUE package with additional configuration first, and then configure
    npm i vuex 
Copy the code

Configuration:

Create a store folder in the SRC root

Put the specific code in store/index.js as follows:

Inject store into the Vue instance

In the SRC/main. In js:

  1. Import store
  2. And inject the Vue instance
Import store import store from './store' new Vue({// omit other... Store // 2. Inject Vue instance})Copy the code

2. Use custom configuration items in a new project. When creating a project in the vuE-CLI configuration, you can directly select the Vuex item so that you don’t have to do any configuration (scaffolding will do it for us automatically). The details are as follows:

Use stores in components

In any component, public data is retrieved through this.$store.state

Vuex learning content

There are five things to learn from Vuex:

  1. State: define public data(similar to data(){return {a:1, b:2, XXXXXX}})
  2. Mutations: Use it to modify data (similar to methods)
  3. Getters: Similar to computed properties (computed properties, computed from existing state to obtain new data ——- derived)
  4. Actions: Initiates asynchronous requests
  5. Modules: modules are split

The most important contents are state and mutations

State —- saves public data

The role of the state

Vuex uses it to store public data

  1. How do I use state globally

Format: new vuex.store ({state: {attribute name: attribute value}})

Using public data

Format:

In the component, it is accessed by the this.$store.state. Property name.

In a template, you can omit this and write: {{$store.state. The property name}}

Code examples:

It could be an object, it could be an array

summary

State is used to hold public data (data shared by multiple components)

State is reactive: if you modify the data, the corresponding value on the view changes.


Mutations —- modifies public data

Function:

Modify the public data defined in state by calling mutations

Definition format: as follows

new Vue.store({
  // omit other...Mutations: {// Each item is a function that can declare two parametersMutation,1:function(State [, load]) {}, mutation2:function(State [, load]) {},}})Copy the code

Each item is a function that can declare two parameters:

  • The first parameter is required to represent the current state and is not passed in for use
  • The second parameter is optional and represents payload. It can be any type of value

Use the format

this.$store.commit('mutation of', argument, given the second argument)Copy the code

Commit here is the fixed method

Example:

Getters —- evaluates to new data – derived

role

On the basis of the data in state, the new data can be obtained by further processing the data. (Same as computed in the component)

  • Define data:
  • Provides methods to get/modify data

For example: Calculate the total price

new Vuex.store({
  state: {
    books: [{"name": "Inside Javasript Technology"."price": 100."img": "https://img3m7.ddimg.cn/64/26/29120617-1_u_8.jpg"
      },
      {
        "name": "The Beauty of Mathematics"."price": 44."img": "https://img3m2.ddimg.cn/18/30/28538352-1_b_5.jpg"
      },
      {
        "name": "Cognitive nature"."price": 40."img": "https://img3m3.ddimg.cn/74/33/1732997153-3_u_3.jpg"}]}})Copy the code

Define the format

new Vuex.store({
  // omit other...
  getters: {
    // State is the public data state defined aboveThe name of the getter1: function(state) {
      returnValue to return}}})Copy the code

State is the public data state defined above

Use the format

It is accessed in the component by the name: $store.getters. Getter

summary

Its purpose is to derive new data items from existing public data items, similar to computed data

Actions —- sends asynchronous requests

role

We can modify state using Action, which is similar to mutation, except that:

  • Instead of changing the state directly, the state must be changed in the action by calling mutation.
  • An action can contain any asynchronous (such as an Ajax request) action.

Define the format

new Vuex.store({
  // omit other...
  actions: {
    // The context object is passed in automatically and has the same methods and attributes as the Store instanceAction name:function(The context, the load) {
      // 1. Send an asynchronous request for data
      
      // 2. commit calls mutation to modify/save the data
      
      // context.com MIT ('mutation name ', payload)}}})Copy the code

Parameters:

Action name: function(context, payload) {

The first argument: context, the executing context object, is equivalent to the running instance of this.$store Store in the component

}

Call format

Pass through the componentThis.$store.dispatch(' Name of actions ', parameter)To invoke the action

Code sample

// Make an Ajax request to fetch data from the back end and then modify the data in state
    actions: {
      getBooks (context, params) {
        console.log('The query parameter for getBooks is', params)
        axios({
          url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books'.method: 'GET'
        }).then(res= > {
          console.log(res)
          context.commit('setBooks', res.data.data)
        })
      }
    },
Copy the code

summary

Action is usually used to make asynchronous requests, and when the data comes back, call mutations to save the data

Putting Ajax requests in actions has two benefits:

  • The code is further encapsulated. Bind sending Ajax and saving data to VUex together.
  • Logic is smoother. If data needs to be stored in Vuex’s state, the action to retrieve data from the interface is defined in Vuex’s Actions.

Modules —- to break down complex businesses

The role of the modules

Split templates, breaking down complex scenarios into modules

format

export default new Vuex.Store({
  // state: Used to store all public data
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {module name1: {// namespaced is true, so when you use mutations, you must add the module name
      	namespaced: true.state: {},
  			getters: {},
  			mutations: {},
  			actions: {},
  			modules: {}}, module name2: {// namespaced is not written, and the default is false, so when using mutations, you don't need to add the module name
  		  state: {},
  			getters: {},
  			mutations: {},
  			actions: {},
         modules: {}}}})Copy the code

Adjustments to access data and modify data

  • To access data in a module, add the module name

    Get the data item: {{$store.state. Module name. Getters: {{$store. Getters [' module name /getters name ']}}Copy the code
  • Access mutations/ Actions in the module:

    • If namespaced is true, you need to add an additional module name
    • If namespaced is false, no additional module name is required
    $store.com MIT ('mutations name ') // namespaced is false. $store.com MIT ('mutations name ') // namespaced is trueCopy the code

summary

Once you use modules, you need to add the modules name when accessing data.

Conclusion: When using Modules, we recommend adding namespaced!