Three minutes to master vuex

Keywords: Vue.js

1. Learning vuex objectives            

  •   Know what vuex is and what it does
  • The use of the 𻚅 parameter in vuex
  • Simplify the use of vuex using the map helper
     

2. What is vuex?

Concept:

  • vuex is a development tool of centralized state management mode, which uses centralized management to solve the communication between multiple arrays

  • Data changes are responsive

3. Basic use of five parameters in vuex

        3.1 state ---- function: save public data

//1. Define in the store instance
const store = new Vuex({
    state: {
        name: 'zs',
        age: 18
    }
})
//2. Call in the component  
this.$store.state.name  //zs

        3.2 variations --- function: modify public data          

          Note: if you want to modify the data of state in vuex, you must call the method in changes to change the public data   Code demonstration:

        

//Defined in the store instance
const store = new Vuex({
    state: {name:'zs'},
    mutations: {
        //state represents the data in the store instance, and the second parameter represents the passed in parameter
        btn(state, newName) {
            state.name = newName
        }
    }
})
//Use in components
this.$store.commit('btn','ww')  //Call the btn method in the changes in the store instance

3.3 getters - function: the data in the processing state is similar to the calculated calculation attribute in vue     Code demonstration:

//1. Define in the store instance
const store = new Vuex({
    state: {},
    mutations: {},
    getters: {
        getSum(state) {
            return state.books.reduce((sum, item) => sum + item.price, 0)
        }
    }
})
//2. Call in the component
this.store.getters.getSum  //Total price

three point four   actions - asynchronous operations are mainly used to send asynchronous ajax requests

        

//1. Define the context parameter in the store instance to point to the current store instance object. You can call context.commit (method name in changes, passed in parameters) to modify the data in state
// You must call the method in changes to modify the data in state
const store = new Vuex({
    state: {},
    mutations: {},
    getters: {},
    actions: {
        async action1(context) {
            const res = await axios({
                url: "https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books",
            })
        }
    }
})

3.5 modules usage steps

  • Role: responsible for the development of modular and component businesses
  • Usage steps: 1. Create a new module component and extract the code of the function module to be extracted
  • 2. in the detached module, the default exported object header line is set namespace:true to true, which means that the module name false is added to the component without adding the module name.
  • 3. Define the module in the store instance and set the namespace attribute
  • 4. Introduce detached modules into the store instance file and mount them on modules in the format of key:value
  • code:
//module/books.js
import axios from 'axios'
export default {
    // It is recommended to add the attribute named to true to access the state. The module name should be written in front of it, and false should not be written
    namespaced: true,
    state: {
        books: [],
        name: 'Journey to the West',
    },
    mutations: {
        updataBooks(state, newBooks) {
            state.books = newBooks
        },
    },
    getters: {
        getSum(state) {
            return state.books.reduce((sum, item) => sum + item.price, 0)
        }
    },
    actions: {
        action1(context) {
            // context points to the current store instance 
            axios({
                url: "https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books",
            }).then(res => {
                context.commit('updataBooks', res.data.data)
                console.log(context.state.books);
            })
        }
    }
}
//   store/index.js
//Introduction module
import books from './modules/books'
//Mount
const store = new Vuex({
    state: {},
    mutations: {},
    getters: {},
    actions: {},
    module: {
        books  //es6 simplified syntax
    }
})
//Used in app.vue component
//  1. The module uses state this. $store. State. Module name. Attribute name
		<h2>title:{{ $store.state.books.name }}</h2>

//	2. The module uses changes this. $store. Module name. commit('method name ', parameter)
		<button @click="$store.commit.books('btn', 'www')">Global call mutations</button>

//  3. The module uses getters this. $store. Getters ['module name / attribute name']
		 <h2>Total price{{ $store.getters["books/getSum"] }}</h2>

//  4. The module uses actions this. $store. Dispatch ('module name / action name ')

4. Use of map auxiliary tools

Function: optimize the access method -- we access the state, changes, etc. in vuex in the component by accessing the $store.state. Attribute name
            So can we optimize this code access   The answer is yes: import the map file in vuex -- import {mapState} from 'vuex' through on-demand import
            One note:
            state and getters are defined in the component calculation attribute computed**
            Changes and axios are defined in component methods  ... It is an extension operator, which is equivalent to expanding and mounting the object on the computed body to directly access the calculation properties**

4.1 map usage of state

//1. Import the map file into the component as needed
import {mapState} from 'vuex'
//2. Defined in computed
computed: {
    ...mapState("books", { bkname: "name" }),  //The modified name books is the module name
    ...mapState(books,['name'])               //Use directly without modifying the name
    
  },
 //After the definition is completed, you can directly use the modified name, directly use the modified name, and directly use the unmodified name without modification  
 //At this time, the name variable has been attached to the calculated attribute. Do you mind using it directly
 <h1>{{bkname}}</h1>  
 <h1>{{name}}</h1>

4.2 map usage of Getters

//1. Introduce map files into the component as needed, and separate multiple files with commas
import {mapGetters,mapState} from 'vuex'
//2. Define in calculation attribute
computed: {
     ...mapGetters("books", { sum: "getSum" }), //Modified that the incoming name is attached to the calculated calculation property
  },
   <h1>{{sum}}</h1>  

4.3 map usage of changes

//1. Import the map file into the component as needed
import {mapGetters,mapState,mapMutations} from 'vuex'
//2. Define in metals
methods:{
    ...mapMutations({btnName:'btn'})  //Changed the method name in the store instance and mounted it to the current vue instance 
}
//It can be called directly in the event 
  <button @click="btnName('zsss')">map Call by</button>

4.4 map usage of actions:

//1. Import the map file in the component as needed
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
//2. Define in metals
methods:{
        ...mapActions("books", { ajax: "action1" }), //Changed name
}
 //It can be called directly
  <button @click="$store.dispatch('books/action1')">Global initiation ajax request</button>

That's all   The following is the diagram of today's homework understanding

 

 

Posted by rhunter007 on Tue, 28 Sep 2021 14:18:41 -0700