One, foreword

How do you use VUex in your project? I used to write it unmodular, and you probably do the same thing, but if you go back and look at the documentation for VUE, it’s better to use vuex modular. Vue is a single page application, and there’s only one page, so the home page or the list page, that’s a module of the page. It can also be understood as one component by one. After all, componentization, component extraction and component encapsulation are popular, so vuEX modularization can be used to better manage corresponding modules, which is very good for data separation and positioning. A little too much nonsense. Let’s throw in a picture.

Demo connection: github.com/cookie-zhan…



Communicating with each other was cumbersome, so vuex was born.

What is Vuex?

Some say it’s a plugin, some say it’s a repository. Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. In fact, it is vUE to do data management, better storage data, response data.

When is the best time to use Vuex?

To quote the official language: Vuex helps us manage shared state and comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits. Using Vuex can be tedious and redundant if you don’t plan to develop large, single-page applications. That’s true — if your application is simple, you’d better not use Vuex. A simple Store model is all you need, but if you need to build a large single-page application and you’re likely thinking about how to better manage state outside of components, Vuex will be a natural choice.

Four, according to the diagram of principle



Four core modules:

  1. State: State is actually a data state management object, where you can initialize some data that you want.
  2. Getter: translation: getter, getter is to read the data object of state, getters means “get” from the surface, it can be regarded as a kind of re-editing before obtaining data, equivalent to a filtering and processing of data. Getters are like computed properties; the return value of the getter is cached based on its dependencies and recalculated only if its dependencies change
  3. In Actions, we can define the method that we want to implement asynchronously, and in this case, it doesn’t execute immediately, but dispatch the method on the page, submit mutations, rather than directly change the status. There are two ways to do that on the page this.$store.dispatch('xxx')The second one can be usedmapActionsThe helper function maps the component’s methods tostore.dispatchCall (shown in the Demo)
  4. Mutations, there can be many ways to change the state, that is, like translation, can change the data in the state, the only way to change the data in the state.

Five, the Demo

We won’t talk about initializing the project, but just build it step by step from the documentation

  • Directory structure:



The page display





Modular data

First, create the modudel folder in store and create homedatastore. js and listdatastore. js respectively. These two modules store the data of corresponding pages respectively. So let’s take the list page as an example.

Listdatastore.js code display

import axios from 'axios'
const listData = {
    namespaced:trueState :{List:[], count: 0, compoentData:[], number: 0 }, actions:{ getListData(context){ new Promise((resolve,reject)=>{ axios.get('.. /.. /.. /static/listData.json').then((res)=>{
                    context.commit('ListData', {'listDatas': res.data.listData})
                })
            })
        },
        handleAdd(context){
            context.commit("handleAddState")
        }
    
    },
    mutations:{
        ListData(state, paylod){
            state.List = paylod.listDatas
        },
        handleAddState(state){
            state.number++;
        }
    },
    getters: {
        List: state => state.List,
        count: state => state.count,
        number: state => state.number
    }
}
export default listData;
Copy the code

The data format is the same, and each page is made up of these four core modules

The index.js file is displayed under the store folder

// This is the total store, throw each module store import Vue from'vue'
import Vuex from 'vuex'
import homeData from './moudel/homeDataStore'
import listData from './moudel/listDataStore'
Vue.use(Vuex)
const store = new Vuex.Store({    
modules:{ 
       homeData,
        listData,
    }})export default store;Copy the code

This is where the data for each module is introduced.

Main.js file display

import Vue from 'vue'
import App from './App'
import router from './router'
import store from  './store/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({ 
 el: '#app',  
router,  
store,  
render: h => h(App)
})
Copy the code

Import store, register store to vue instance, so the basic format of the corresponding module data is like this, next we will see how to call the page.

The page is displayed using the Store data list page

<template>
 <div> 
<router-link to='/'> home</router-link><br/> This is the list page list<br/> <ul> <li v-for="item in List" v-bind:key="item.id"> {{item. Item}} < / li > < / ul > < div > : < / div > < div > {{number}} < / div > < button @ click ='handleAdd()'>add</button> 
   </div></template><script>
import { mapGetters, mapActions } from 'vuex'
export default {    
name: 'list'.data() {return{} }, computed:{ ... mapGetters('listData'['List'.'number'}, {//... mapActions('listData'['getListData'.'handleAdd'], // Method two... mapActions({ getListData:"listData/getListData",            
     handleAdd:"listData/handleAdd"})},mounted(){        
   this.getListData();    
}}
</script>
<style></style>Copy the code

Import {mapGetters, mapActions} from ‘vuex’ to get the List number for the store of a List page in computed attributes, / / Mounted getListData (mounted) {/ / mounted () {/ / mounted () {/ / mounted () {/ / mounted () {/ / Mounted () {/ / Mounted () {/ / getListData () {/ / Mounted () {/ / Mounted () {/ / Mounted () {/ / Mounted () {/ / Mounted (); The handleAdd method is also dispatched, which can be seen in the corresponding actions. If you don’t use helper functions, you also use dispatch, which I won’t go into here

Demo address: github.com/cookie-zhan…

Six summarize

The above description is easy to understand, and you can use this modular way of managing data directly in your project. Overall, you can better understand the FLOW chart of VUX, one-way data flow can form a perfect closed loop. Not too much literary talent, just want to use the latest single understandable language to describe their own understanding, if you can help you so a didiao, please give me a small praise!