preface

Componentized application construction is one of the characteristics of Vue, so we often need to encapsulate custom components in the actual development process of Vue to improve the efficiency of development. Components, for the most part, do not exist in isolation; they must interact with their parent and sibling components. There are two ways to interact with component data: EventBus and state management using the Vuex framework.

The previous article described how EventBus can be used for event passing in a Vue custom component (Vue Custom Component Event Passing: The EventBus section), which is more suitable for small to medium sized projects. If we need to develop a large project, we should consider using the Vuex framework for unified data state management.

In order to help readers understand the basics of using Vuex, I will continue to use the example from the previous article (obviously Vuex is not necessary in single page and small to medium sized applications) to introduce you to the use of Vuex.

Why use Vuex when you have EventBus

Why are we using Vuex when we have EventBus?

In fact, there is a good explanation on the official website of Vuex: What is Vuex

My understanding of what Vuex is is:

Vuex is a data state management framework that decouples the data and view layers

Why do we use Vuex when there is EventBus? My understanding is as follows:

When we use EventBus, control A will transfer data to control B and control C, and control B will modify the data after processing, and continue to inform control A and control C to modify the data. In this way, the EventBus of CONTROL A and control B will be monitored in multiple places in the C file. So when there is a bug in the data delivery, it is very difficult to track down exactly what went wrong.

As the complexity of our business increases, so does the complexity of our views, it becomes necessary to decouple the data and view layers through Vuex.

Case Description (same as the previous case “Vue Custom Component Event Passing: The EventBus Section “, can be skipped)

There are plenty of code examples in this section, but the following table of contents and components are provided to make reading easier. This section mainly uses two child components and a parent component.

Subcomponent file names: searchinput.vue and searchItem.vue

Parent component file name: stateview.vue

Directory structure display:

1, SearchInput. Vue

Component description: an input box, it will onInput method to listen for input content, and call the method, the input box data passed out.

Code display:

<template>
  <div>
    <input placeholder="Search content"  v-model="searchContent"/>
  </div>
</template>

<script type="text/ecmascript-6">
  export default{
    data() {return{
        searchContent:""
      }
    },
    props:{

    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>


Copy the code

SearchItem.vue

Component introduction: A SPAN that receives content from the parent component and receives content from the sibling component’s input box and displays it.

Code examples:

<template>
    <span class="item">
      {{content}}
    </span>
</template>

<script type="text/ecmascript-6">
  export default{
    data() {return{
        content:this.itemContent
      }
    },
    props:{
      itemContent:{
        type:String,
        required:true
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .item
    background #f4f4f4
    padding 3px 5px
    box-sizing border-box
    display inline-block
    cursor pointer
</style>

Copy the code

StateView.vue

Component introduction: The parent component, mainly displays the page and loads the child components

Code examples:

<template>
  <div>
    <search-view></search-view>
    <div>
      <search-item :itemContent="content"/>
      <search-item itemContent="Hot Search 2"/>
      <search-item itemContent="Hot Search 3"/>
    </div>
    <div>{{content}}</div>

  </div>
</template>

<script type="text/ecmascript-6">
import searchView from '.. /components/SearchInput.vue'
import searchItem from '.. /components/SearchItem.vue'

export default{
  data () {
    return {
      content:"Receive the value of the input field"
    }
  },
  components: {
    searchView,
    searchItem
  }
}

</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

Copy the code

The body of the

Globally register Vuex

Before we start introducing Vuex, we need to register a Vuex object globally.

View our directory structure:

1. Create Store file

We created a Store folder for store files of various types.

Here we create the searchStore.js file. It will be our main protagonist for the rest of our Vuex State, Getter, Mutation, and Action.

The searchStore.js code looks like this:

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
})

Copy the code

2. Inject searchStore.js into main.js

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import vueResource from 'vue-resource'
import searchStore from './store/SearchStore'// Import searchStore.js vue. use(vueResource) vue.config.productionTip =false

/* eslint-disable no-new */
new Vue({
  el: '#app', router, store:searchStore, // Inject searchStore Components: {App}, template:'<App/>'
})

Copy the code

We introduced the searchStore. js file in main.js and injected the searchStore. js file into the Vue root component, so that all child components can access the searchStore.js Store.

State

State is like a global data store that holds data sources

How to understand this sentence?

Don’t worry, let’s look at a Demo, and you’ll understand State a little bit.

We modify the searchStore.js file to add a data store State to it:

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
  state:{
    searchContent:"This is the searchContent of the Store."}})Copy the code

Mounted () in stateView.js and searchinput.js to print searchContent in searchStore.js:

StateView

<template>
  <div>
    <search-view></search-view>
    <div>
      <search-item :itemContent="content"/>
      <search-item itemContent="Hot Search 2"/>
      <search-item itemContent="Hot Search 3"/>
    </div>
    <div>{{content}}</div>

  </div>
</template>

<script type="text/ecmascript-6">
import searchView from '.. /components/SearchInput.vue'
import searchItem from '.. /components/SearchItem.vue'
import searchEvent from '.. /event/SearchEvent'
export default{
  data () {
    return {
      content:""}},mounted(){
    console.log("StateView======"+this.$store.state.searchContent) // Print searchContent in SearchStore}, components: {searchView, searchItem}} </script> <style lang="stylus" rel="stylesheet/stylus">

</style>

Copy the code

SearchInput.js

<template>
  <div>
    <input placeholder="Search content" @input="sendEvent" v-model="searchContent"/>
  </div>
</template>

<script type="text/ecmascript-6">
  import searchEvent from '.. /event/SearchEvent'
  export default{
    data() {return{
        searchContent:""}},mounted(){
      console.log("SearchInput======"+this.$store.state.searchContent)
    },
    props:{

    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

Copy the code

Console output

So, how’s it going? Do you have feelings for State?

Conclusion:

1. State is a repository where all data sources are stored, just like data in a component.

Js state can be accessed from any component using this.$store.state, rather than calling $emit and $ON methods to listen for and copy data, as in EventBus. The data and view layers are decoupled.

Getter

The Getter is used to retrieve the data source, perform some processing on the data source, and then return it.

Next we add the Getter to searchStore.js to get a feel for what this statement means.

SearchStore.js

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
  state:{
    searchContent:"This is the searchContent of the Store."}, getters:{// Add getter getSearchContent(state){// We define a getter function called gerSearchContent, which takes one parameter, which holds the state object. // Is the state object of searchStore.jsreturn "Processed searchContent===="+state.searchContent // simulate processed data and return processed data}}})Copy the code

In this case, we define a function called getSearchContent in the Store getters that takes one parameter, which is our state object, in this case, the searchStore.js state object.

Then we simulate the process of data processing and return a data after data processing.

Next, let’s print the getter in StateView’s Mounted () life cycle.

StateView.js

<template>
  <div>
    <search-view></search-view>
    <div>
      <search-item :itemContent="content"/>
      <search-item itemContent="Hot Search 2"/>
      <search-item itemContent="Hot Search 3"/>
    </div>
    <div>{{content}}</div>

  </div>
</template>

<script type="text/ecmascript-6">
import searchView from '.. /components/SearchInput.vue'
import searchItem from '.. /components/SearchItem.vue'
import searchEvent from '.. /event/SearchEvent'
export default{
  data () {
    return {
      content:""}},mounted(){
    console.log("StateView======"+this.$store.state.searchContent) // Print searchContent console.log("StateView======"+this.$store. Getters. GetSearchContent) / / print SearchStore getSearchContent} of the components: { searchView, searchItem } } </script> <style lang="stylus" rel="stylesheet/stylus">

</style>
Copy the code

The console output

Getter’s feeling conclusion

1. Getter is mainly used to obtain data and return the data after processing.

2. Compared with EventBus, through the Getter of Vuex, we can uniformly process data in Store, which is conducive to future project maintenance.

Mutation

Modify the data in the data warehouse. Mutation only supports synchronous methods

Again, we get a feel for Mutation by adding it to searchStore.js

SearchStore.js

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
  state:{
    searchContent:"This is the searchContent of the Store."
  },
  getters:{
    getSearchContent(state){
      return "Processed searchContent===="+state.searchContent } }, Mutations :{changeSearchContent(state,payload){** ** transfer a single data parameter */ state.searchContent=payload {}, changeSearchContentByObject (state, content) / * * * sometimes we need to be content to pass multiple data parameters, we can be passed through the way of object * / state in searchContent ="Modify data with Object:"+payload.searchContent
    }
  }
})
Copy the code

Note: the only difference between the two Mutation methods is that the payload accepted is a single parameter. And when you have to pass multiple parameters, you can pass multiple parameters in the way you pass objects in the payload.

Next, we’ll still modify stateView.js.

StateView.js

<template>
  <div>
    <search-view></search-view>
    <div>
      <search-item :itemContent="content"/>
      <search-item itemContent="Hot Search 2"/>
      <search-item itemContent="Hot Search 3"/>
    </div>
    <div>{{content}}</div>

  </div>
</template>

<script type="text/ecmascript-6">
import searchView from '.. /components/SearchInput.vue'
import searchItem from '.. /components/SearchItem.vue'
import searchEvent from '.. /event/SearchEvent'
export default{
  data () {
    return {
      content:""}},mounted(){
    console.log("StateView======"+this.$store.state.searchContent) // Print searchContent console.log("StateView======"+this.$store. Getters. GetSearchContent) getSearchContent / / / / print SearchStore through this.$storeThe.commit() method modifies state's searchContent parameter // passing the single parameter this in payload.$store.commit("changeSearchContent"."Modified SearchContent in StateView")
    console.log("StateView======"+this.$store.state.searchContent) // When we need to pass multiple parameters, we can pass this as an object in payload.$store.commit("changeSearchContentByObject", {"searchContent":"Modified SearchContent in StateView"."testVal":"testVal"})
    console.log("StateView======"+this.$store.state.searchContent)
  },
  components: {
    searchView,
    searchItem
  }
}

</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>
Copy the code

In statevie.js, we call the mutations method with the this.store.mit () method, which takes two arguments:

2. the second parameter delivers the payload, which is the data to be sent

The console output

Conclusions of Mutation:

1. From Mutation, we can modify the data in the data warehouse. We can call this.code.store.mit () method in the build to call the corresponding Mutation to modify the data.

2, Mutation only performs synchronous methods. If you need to perform asynchronous methods, use the upcoming Action.

Action

Actions are similar to Mutation in that they commit mutations instead of directly changing the state. 2. Actions can contain any asynchronous Action.

Without further ado, let’s directly modify the searchStore.js file:

SearchStore.js

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
export default new vuex.Store({
  state:{
    searchContent:"This is the searchContent of the Store."
  },
  getters:{
    getSearchContent(state){
      return "Processed searchContent===="+state.searchContent } }, Mutations :{changeSearchContent(state,payload){** ** transfer a single data parameter */ state.searchContent=payload {}, changeSearchContentByObject (state, content) / * * * sometimes we need to be content to pass multiple data parameters, we can be passed through the way of object * / state in searchContent ="Modify data with Object:"+ content. SearchContent}}, actions: {changeSearchContentByAction (the context, content) {/ * * * to simulate asynchronous process, 2000 milliseconds later through the commit () method performs mumations changeSearchContentByObject method change data of * in the same way, content can be single or through the way of object data, Passing multiple data * This is just an example of passing multiple data through objects */setTimeout(()=>{
        context.commit("changeSearchContentByObject",payload)
      },2000)
    }
  }
})
Copy the code

Here we simulate an asynchronous process, changing the searchContent data by calling setTimeOut() and then calling commit() after 2000 milliseconds.

Next we to modify the StateView. Js to invoke the changeSearchContentByAction we just wrote

StateView.js

<template>
  <div>
    <search-view></search-view>
    <div>
      <search-item :itemContent="content"/>
      <search-item itemContent="Hot Search 2"/>
      <search-item itemContent="Hot Search 3"/>
    </div>
    <div>{{content}}</div>

  </div>
</template>

<script type="text/ecmascript-6">
import searchView from '.. /components/SearchInput.vue'
import searchItem from '.. /components/SearchItem.vue'
import searchEvent from '.. /event/SearchEvent'
export default{
  data () {
    return {
      content:""}},mounted(){
    console.log("StateView======"+this.$store.state.searchContent) // Print searchContent console.log("StateView======"+this.$store. Getters. GetSearchContent) getSearchContent / / / / print SearchStore through this.$storeThe.commit() method modifies state's searchContent parameter // passing the single parameter this in payload.$store.commit("changeSearchContent"."Modified SearchContent in StateView")
    console.log("StateView======"+this.$store.state.searchContent) // When we need to pass multiple parameters, we can pass this as an object in payload.$store.commit("changeSearchContentByObject", {"searchContent":"Modified SearchContent in StateView"."testVal":"testVal"})
    console.log("StateView======"+this.$store.state.searchContent) // Modify the data this with Action.$store.dispatch("changeSearchContentByAction", {"searchContent":"Action modified data"})
    setTimeout(()=>{
      console.log("5000 ms later StateView======"+this.$store.state.searchContent)
    },5000)
    
  },
  components: {
    searchView,
    searchItem
  }
}

</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>
Copy the code

In stateView.js, we call the action through the this.$store.dispatch() function, which takes two parameters: the name of the method in the store action, and the data to be passed

** Console output **

Conclusion:

Action is similar to Mutation, except that it can handle asynchronous cases and eventually modify the data with a commit() call.

Call the Action method with this.$store.dispatch().

Module

You can modularize stores and then pull them together through modules.

If we write all of our data into a Store state, then we fetch and modify the data. As the project grew, the number of states and mutations, getters, actions, and lines of code in our Store exploded, making our Store difficult to maintain.

At this point, we want to modularize the Store, such as extracting data from different sub-components into a single Store.

At this point we need to integrate the modules through Module and then hang the Store under the root component.

Now, instead of using SearchStore as an example, we create three new Store files:

1. Index. js Store, mainly responsible for integrating all Store modules.

2, SearchinputStore. js, mainly responsible for the input block sub-component searchinput.js data maintenance

3. Searchitemstore. js, mainly responsible for the data maintenance of searchItem. js sub-components

Searchinputstore.js and searchitemstore.js:

SearchInputStore.js

export default {
  state: {
    searchContent:""
  },
  getters:{
    getSearchContent(state){
      return state.searchContent;
    }
  },
  mutations:{
    changeSearchContent(state,payload){
      state.searchContent=payload
    }
  }
}
Copy the code

SearchItemStore.js

export default {
  state: {
    searchHistoryList:[]
  },
  getters:{
    getsearchHistoryList(state){
      return state.searchHistoryList;
    }
  },
  mutations:{
    changesearchHistoryList(state,payload){
      state.searchContent.push(payload)
    }
  }
}
Copy the code

Here, we just export SearchInputStore and SearchItemStore with export Default.

Next let’s look at index.js, which combines searchinputStore.js with searchitemStore.js

index.js

/**
 * Created by Vicky on 2018/6/22.
 */
import Vue from 'vue'
import vuex from 'vuex'
import searchInputStore from './SearchInputStore'
import searchItemStore from './SearchItemStore'
Vue.use(vuex)
export default new vuex.Store({
  modules:{
    searchInputStore:searchInputStore,
    searchItemStore:searchItemStore
  }
})

Copy the code

In index we import searchinputStore. js and searchitemstore. js as import, and then in Store modules.

Next we’ll mount index.js under the root component, and we’ll modify main.js:

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import vueResource from 'vue-resource'
import store from './store/index'// reference index.js // import searchStore from'./store/SearchStore'
Vue.use(vueResource)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app'Router: {App}, template:'<App/>'
})
Copy the code

We have successfully integrated the two Store modules. Note that we need to add the module name when accessing the state object:

For example, we want to visit SearchInputStore searchContent data, we need to use this. $store. State. SearchInputStore. SearchContent for a visit.

namespaced: true

Namespaced is mainly used to improve module encapsulation and reuse

When we call commit(), Mutation, getters, and actions of the same method name will be called. When we repeat the name of our Getter method, we get an error; When we call the dispatch() method, all actions with the same method name will be executed.

This is obviously not logical, and it will pollute the data of other modules and cause anomalies. However, in a large project, we tend to collaborate with many people, so it’s hard to avoid everyone defining Mutation, getters, and actions with the same name without telling them.

At this point, we need Namespaced to do us the favor of increasing module encapsulation and reusability.

Next we will modify the index.js and searchinputStore.js files:

index.js

import Vue from 'vue'
import vuex from 'vuex'
import searchInputStore from './SearchInputStore'
import searchItemStore from './SearchItemStore'
Vue.use(vuex)
export default new vuex.Store({
  state:{
    rootVal:"Value of root Store"
  },
  getters:{
    getRootVal(state){
      return state.rootVal
    }
  },
  mutations:{
    changeRootVal(state,payload){
        console.log("The root Store's changeRootVal has been called.")
        state.rootVal=payload
    }
  },
  actions:{
    changeRootValByAction(context,payload){
      console.log("The root Store's changeRootValByAction was called.")
      context.commit("changeRootVal",payload)
    }
  },
  modules:{
    searchInputStore:searchInputStore,
    searchItemStore:searchItemStore
  }
})


Copy the code

We added State, Getter, and Mutation to index.js to demonstrate that after a substore wraps its data module with namespaced data, How the child Store accesses the Getter of the root Store, and how root Mutation and child Mutation are called by commit(); How to invoke root Action and child Action via Dispatch ().

SearchInputStore.js

export default {
  namespaced:true,
  state: {
    searchContent:""}, Getters: {getSearchContent (state, getters, rootState rootGetters) {/ * * * state represents the state of the current module getters * * getters represents the current module RootState represents the root Store state, namely, index, js Store, but also contains its Store, we can through rootState. SearchItemStore searchInputStore access; Access the State value of the root module by rootstate. rootVal. * rootGetters representing the root Store getters and its child Store getters are also mounted under rootGetters, * we can use rootGetters[rootGetters["searchItemStore/getHistoryList"] to access the getHistoryList in searchItemStore * to access the getRootVal in the root module */ / / to access through rootState searchItemStore State data of the console, log (rootState. SearchItemStore. SearchHistoryList) // Use rootState to access State data console.log(rootstate.rootval) // Use rootGetters to access the Getter of searchItemStore console.log(rootGetters["searchItemStore/getHistoryList"[rootgetters.getrootVal] // Access getRootVal console.log(rootgetters.getrootval)returnstate.searchContent; }, mutations:{changeSearchContent(state,payload){** ** state represents the state of the current module ** **"searchItemStore/changeHistoryList",payload) call changeHistoryList this.mit ("searchItemStore/changeHistoryList",payload) // this.mit ("changeRootVal",payload) call the root module's changeRootVal this.mit ("changeRootVal",payload)
      console.log("ChangeSearchContent is called.") state.searchContent=payload } }, actions:{ changeSearchContentByAction(context, Payload){// Call this module changeSearchContent context.com MIT ("changeSearchContent"// Call the otherAction context.dispatch("otherAction"// Call the root Mutation and Action only by passing in the third parameter object,{root:true} to MIT (context.com"changeRootVal",payload,{root:true}) // Call the root node's changeRootValByAction context.dispatch("changeRootValByAction",payload,{root:true})
    },
    otherAction(context,payload){
      console.log("OtherAction is called.")}}}Copy the code

SearchItemStore

export default {
  namespaced:true,
  state: {
    searchHistoryList:["Historical Record 1"]
  },
  getters:{
    getHistoryList(state){
      return state.searchHistoryList;
    }
  },
  mutations:{
    changeHistoryList(state,payload){
      state.searchHistoryList.push(payload)
    }
  },
  actions:{
    changeHistoryListByAction(context,payload){
      context.commit(changeHistoryList,payload)
    }
  }
}

Copy the code

We’ve wrapped the module with namespaced: True.

Since SearchInputStore and SearchItemStore are encapsulated, how should our child components access SearchInputStore? How does SearchInput access the State, getters, mutations, and actions of other encapsulated modules and root stores?

How child components access encapsulated modules (using SearchInputStore as an example)

Access to the State

When accessing encapsulated State data, we only need to make the following changes **(take accessing searchContent of SearchInputStore for example) ** :

This $store. State. SearchContent change into this. $store. State. SearchInputStore. SearchContent

Visit the Getter

(Take accessing getSearchContent of SearchInputStore as an example) :

This $store. Getters. GetSearchContent change into this. $store. Getters [” searchInputStore/getSearchContent “]

Access to the Mutation

(Take accessing the SearchInputStore’s changeSearchContent as an example):

This.com MIT (” changeSearchContent “, “new data”) change into this.$store.com MIT (” searchInputStore/changeSearchContent “, “new data”)

Access to the Action

For access to SearchInputStore changeSearchContentByAction (for example) :

This dispatch (” changeSearchContentByAction “, “new data”) into this. $store. Dispatch (” searchInputStore/changeSearchContentByAction” ,” New data “)

How encapsulated modules access other encapsulated modules and root modules (using SearchItemStore as an example)

Let’s take a closer look at the following code for SearchInputStore:

SearchInputStore

export default {
  namespaced:true,
  state: {
    searchContent:""}, Getters: {getSearchContent (state, getters, rootState rootGetters) {/ * * * state represents the state of the current module getters * * getters represents the current module RootState represents the root Store state, namely, index, js Store, but also contains its Store, we can through rootState. SearchItemStore searchInputStore access; Access the State value of the root module by rootstate. rootVal. * rootGetters representing the root Store getters and its child Store getters are also mounted under rootGetters, * we can use rootGetters[rootGetters["searchItemStore/getHistoryList"] to access the getHistoryList in searchItemStore * to access the getRootVal in the root module */ / / to access through rootState searchItemStore State data of the console, log (rootState. SearchItemStore. SearchHistoryList) // Use rootState to access State data console.log(rootstate.rootval) // Use rootGetters to access the Getter of searchItemStore console.log(rootGetters["searchItemStore/getHistoryList"[rootgetters.getrootVal] // Access getRootVal console.log(rootgetters.getrootval)returnstate.searchContent; }, mutations:{changeSearchContent(state,payload){** ** state represents the state of the current module ** **"searchItemStore/changeHistoryList",payload) call changeHistoryList this.mit ("searchItemStore/changeHistoryList",payload) // this.mit ("changeRootVal",payload) call the root module's changeRootVal this.mit ("changeRootVal",payload)
      console.log("ChangeSearchContent is called.") state.searchContent=payload } }, actions:{ changeSearchContentByAction(context, Payload){// Call this module changeSearchContent context.com MIT ("changeSearchContent"// Call the otherAction context.dispatch("otherAction"// Call the root Mutation and Action only by passing in the third parameter object,{root:true} to MIT (context.com"changeRootVal",payload,{root:true}) // Call the root node's changeRootValByAction context.dispatch("changeRootValByAction",payload,{root:true})
    },
    otherAction(context,payload){
      console.log("OtherAction is called.")}}}Copy the code
Access State and Getter

Take a look at SearchInputStore’s getters:

We found getSearchContent accept parameters from state to state, getters, rootState, rootGetters, their meaning is as follows:

1. State represents the state of the current module

Getters represents the getters of the current module

3, rootState represents the root Store state, namely index. Js Store, but also contains its Store, we can through rootState. SearchItemStore searchInputStore access; Access the State value of the root module by rootstate. rootVal.

Getters representing the root Store and getters for its substores are also mounted under rootGetters. We can use rootGetters [” searchItemStore/getHistoryList “] to visit searchItemStore getHistoryList module

Access to the Mutation

(Take accessing the SearchInputStore’s changeSearchContent as an example):

In SearchInputStore Mutation, you can pass:

1, this.com MIT (” searchItemStore/changeHistoryList “, content call searchItemStore changeHistoryList root module

This.mit (“changeRootVal”,payload) calls the changeRootVal of the root module

Access to the Action

For access to SearchInputStore changeSearchContentByAction (for example) :

You can call the Mutation and Action of the root module in the Action of the SearchInputStore, but you cannot call the Mutation of other encapsulated modules, otherwise an error will be reported.

In fact, this also makes sense. When the Mutation of this module was completed asynchronously, to modify the data of other modules, we only need to call the Mutation of other modules in our own module, and there is no need to call the Action of other modules.

So we can call the Mutation and Action of this module and the root module via context.mit () and cotext.dispatch() :

1, call the module changeSearchContent:context.com MIT (” changeSearchContent “, content

Call otherAction: context.dispatch(“otherAction”,payload)

MIT (“changeRootVal”,payload,{root:true})

ChangeRootValByAction: context.dispatch(“changeRootValByAction”,payload,{root:true})

The final checking

1. Vuex is a framework for decoupling data and view layers

There is no need to use Vuex for single pages and small projects.

3. State in Vuex is like a global data warehouse where data sources are stored.

4. The Getter in Vuex is used to fetch the data source and then return it after some processing.

Vuex Mutation is used to modify the data in the data warehouse. Mutation only supports synchronous methods.

6. Actions in Vuex are similar to Mutation in that they submit mutations instead of directly changing the status. 2. Actions can contain any asynchronous Action.

7. Modules in Vuex can modularize stores and then integrate them with modules.

About… MapGetters,… MapMutation,… MapActions is not expanded. It is mainly used to simplify code writing by using es6 syntax. Please refer to the official Vuex document

9. After reading this tutorial, it is recommended to read the official documentation again and implement a small Demo by yourself

I am Damai, if you like my article, please give me a careful heart.