Vuex introduction

Vuex usage process

1. Install Vuex:

npm install vuex || yarn add vuex// Either way
Copy the code


2. Create a file

In the/SRC directory, create a directory called store and set an index.js file in that directory as an exit

Specific reference steps:import Vue from "vue"
// Then import the next good vuex package
import Vuex from "vuex"

// Mount vuex to Vue
Vue.use(Vuex)

// Create an instance of vuex.store
const store = new Vuex.Store({
  / / various configuration (similar to the data, the methods, the computed...).
  // State corresponds to the component where data defines public variables
  state: {
    num: 100// This is a public variable}})// 3. Export store instance
export default store

Copy the code

In the main.js file, import:

import Vue from 'vue'
import App from './App.vue'
// Add store to the entry file
import store from './store/index.js'
Vue.config.productionTip = false

// Mount to vue instance
new Vue({
  store: store,
  render: h= > h(App),
}).$mount('#app')
Copy the code


3. Attributes in VUex

new Vuex.Store({
    state: {},geeter: {// is a calculated attribute in VUEX that stores data derived from base data (state)
    },
    mutations: {// The function name can be any valid function name
        // Parameter 1: indicates the current state
        // Parameter 2: optional. This represents the argument passed in when function 1 is called.The function name1(parameter1, the parameter2) {// Inside the function, modify the data in state}},actions: {Context is similar to the $store object
        // Payload is the passed parameter value
        // Must submit mutations in actions to trigger the state update.
        asyncSubNum(context, payload){
            Mutations -> change state after adding an asynchronous task
            setTimeout(() = > {
                context.commit("subNumFn", payload);
            }, 1000); }},modules: {// Store the module name
        // Modular VUEX allows each module to have its own state, mutation, action and getters, making the structure very clear and easy to manage}})Copy the code

4. Use vuEX variables

Method 1: Use by calling the exported Store object
Use variables in templates:'{{$store.state. Variable name}}'Vue page configuration item: when module is not defined -- call variable in state property:`this.$store.state.num`-- Call the method in the mutations property:'this. codestore.mit (' function name ', value to be passed in)'Call asynchronous methods in actions properties:'this.$store.dispatch(' function name ', the value to be passed in)'After defining the module -- call the variable in the state property:'this.$store.state. Module name.num'-- Call the method in the mutations property:'this. codestore.com MIT (' module name/function name ', value to be passed in)'Call asynchronous methods in actions properties:'this.$store.dispatch(' module name/function name ', value to be passed in)'Import the exported store object first:import store from './store/index.js'Call the variable in the state property when the module is not defined:`store.state.num`-- Call the method in the mutations property:'store.mit (' function name ', value to be passed in)'Call asynchronous methods in actions properties:'store.dispatch(' function name ', the value to be passed in)'After defining the module -- call the variable in the state property:'store.state. Module name.num'-- Call the method in the mutations property:'store.mit (' module name/function name ', value to be passed in)'Call asynchronous methods in actions properties:'store.dispatch(' module name/function name ', the value to be passed in)'Call other properties or methods in current VUEX:Vuex recommends modifying the data in store.js in the mutation attribute instead of using $store
    // This is a bit more cumbersome, but allows centralized monitoring of all data changesMutations :{legal function name (state, parameter){// State is recommended for the first parameter name, which is semantically clear, equivalent to mapping the state attribute to use variables in the mutations function,
            / / parameters
            // Change the syntax of the data in state:State. Variable name =... }},actions: {asyncMethod name (context, argument){Context is similar to the $store object
             // Argument 2 is any parameter value passed in
             // If you want to use the methods in mutations
             / / syntax:
             context.commit('Mutations Chinese legal name'And parameters)// The module name is not needed because it is called in the current module
             // Want to use methods in actions
             context.dispatch('Actions Chinese name'And parameters)// To use other module methods, simply append a module name to the method name
              context.commit('Module name /mutations Chinese legal name', parameter) context.dispatch('Module name/Actions Chinese method name'}}, *** Note that after defining the module, you need to set namespace =trueAfter the namespace is enabled, the same method or variable name must carry the module name to avoid confusion caused by the same nameCopy the code
Method 2: Map mapping is used

Mapping: mapState > Computed mapGetters > Computed mapMutations > Methods mapActions > methodsCopy the code

Using the step

Undefined module1.Import mapState functions as needed in the component:`import { mapState } from 'vuex'`
`import { mapMutations } from 'vuex'`
`import { mapGetters } from 'vuex'`
`import { mapActions } from 'vuex'`
2.Map data or methods in VUEX:`computed:{ ... MapState ([' variable names in state ',' multiple comma separated '])} '
`computed`{ ...mapGetters(['Variable name in Getters'])}
`methods:{ ... Open mutations (open mutations)}
`methodus`: {... mapActions(['Method name in Actions'])}
3.To treat the data mapped to a component as a general computed property, you just need to add the module name before the variable name or method name. Example :computed:{... mapState('user'['Variable name in state'.'Multiple separated by commas'])}` / /... MapActions ('user', ['login']) // To avoid the same name as the status value, you can also use the full path, as follows... MapActions ([' user/login ']) / / when to use this [' user/login '] (' admin '). Then (res = > {})Copy the code

The above is my summary, and I hope to correct the deficiencies