In some small projects you don’t have to use Vuex, but in some large projects vuex is a surefire way to make it easy to use and track the state of your view. Write a Store object

define([], function() {
    var Vue = require('vue')
    var Vuex = require('src/libs/vuex/vuex.js')
    Vue.use(Vuex)
    var modelA= require('src/libs/vuex/modelA.js')
    // Apply the initial state
    var state = {
        count: 2
    }

    // Define the mutations needed
    var mutations = {
        INCREMENT: function(state) {
            state.count++
        },
        DECREMENT: function(state) {
            state.count--
        }
    }
// This section can import module objects
     var store = new Vuex.Store({
            state: state,
            mutations: mutations,
            modules: {
                test: modelA
            }
        })
        // Create a store instance
    return store
})Copy the code

2. Vuex in app needs to inject store into the big root directory at startup (i.e. App. vue in vuE-CLI scaffolding). As shown in figure

vuex



store
vue


define([], function() {
    var modelA = {
        state: {name: 3
        },
        // Define the mutations needed
        mutations:{
            INCREMENT: function(state) {
                state.name++
            },
            DECREMENT: function(state) {
                state.name--
            }
        }
    }
    return modelA;
})Copy the code

4, used in child components

vuex: {
        getters: {
            count: state= > state.count// The variable must be placed here. This can also be a function, used as a filter
        },
        actions: {
            increment:function(dispatch){
                dispatch.dispatch('INCREMENT')// Trigger variable modification
            },

            decrement:function(dispatch)
            {
                dispatch.dispatch('DECREMENT')}}},created: function() {},`Copy the code

It can also be used this way

this.$store.dispatch('DECREMENT');// Trigger method
this.$store.commit('DECREMENT');// Trigger method vuex2, the trigger method in actions
this.$store.state.count='ssss';// Change the value of a variable
this.$store.state.test.name='ssss';// Modify the value of the module variableCopy the code

Test example 1. Google Browser console

Test modularized variables

2. Test modularity variables

Modular testing

  • As you can see, Dispatch triggers a function with the same method name
  • Vuex is relatively more modular and traceable than the data defined by Window. Please feel free to talk if you have any questions.