Home  >  Article  >  Web Front-end  >  The Complete Guide to Mapping in Vuex

The Complete Guide to Mapping in Vuex

青灯夜游
青灯夜游forward
2020-10-07 14:18:024702browse

The Complete Guide to Mapping in Vuex

Vuex is a double-edged sword. If used correctly, using Vue can make your job easier. It can also clutter your code if you're not careful.

Before using Vuex, you should first understand four main concepts: state, getter, mutation and action. A simple Vuex state manipulates data within these concepts in the store. Maps in Vuex provide a great way to retrieve data from them.

In this article, I will demonstrate how to map data in Vuex storage. If you're familiar with Vuex basics, this content will help you write cleaner, more maintainable code.

This article assumes you know the basics of Vue.js and Vuex.

What is mapping in Vuex?

Mapping in Vuex allows you to bind any kind of property in state (state, getter, mutation, and action) to a computed property in a component and use the data in state directly.

The following is a simple Vuex store example where the test data is located in state.

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    data: "test data"
  }
})

If you want to access the value of data from state, you can perform the following operations in the Vue.js component.

computed: {
        getData(){
          return this.$store.state.data
        }
    }

The above code works, but as the amount of state data starts to grow, it quickly becomes ugly.

For example:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {
        id:1,
        age:23,
        role:user
        data:{
          name:"user name",
          address:"user address"
        }
    },
    services: {},
    medical_requests: {},
    appointments: {},
    }
  }
})

To get the username from the user object in state:

computed: {
        getUserName(){
          return this.$store.state.user.data.name
        }
    }

This gets the job done, but there is a better way.

Mapping state

To map state to a computed property in a Vue.js component, you can run the following command.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState([
            'user',
        ])
    }
}

Now you can access the entire user object in the component.

You can do more, such as adding objects from state to the mapState method.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState([
            'user',
            'services'
        ])
    }
}

As you can see, this is much cleaner. The username can be easily accessed via:

{{user.data.name}}

services The same goes for many other values ​​of the object and map.

Did you notice how we passed the array to mapState()? If you need to give the value a different name, you can pass in an object.

import { mapGetters } from 'vuex';

export default{
    computed: {
        ...mapState({
            userDetails:'user',
            userServices:'services'
        })
    }
}

can now be referenced by simply calling userDetails. When to map the entire state

As a rule of thumb, you should only map when there is a lot of data in the state and it is all needed in the component.

In the above example, mapping the entire user object doesn't make much sense if we only need one value (e.g.

username

). During mapping, the entire object will be loaded into memory. We actually don't want to keep loading unnecessary data into memory as this will be redundant and will affect performance in the long run.

Mapping getter

The syntax of mapping getter is similar to the

mapState

function. <pre class="brush:js;toolbar:false;">import { mapGetters } from &amp;#39;vuex&amp;#39; export default { computed: { ...mapGetters([ &amp;#39;firstCount&amp;#39;, &amp;#39;anotherGetter&amp;#39;, ]) } }</pre>Similar to mapping state, you can pass the object to the

mapGetters

function if you plan to use a different name. <pre class="brush:js;toolbar:false;">import { mapGetters } from &amp;#39;vuex&amp;#39; export default { computed: { ...mapGetters([ first:&amp;#39;firstCount&amp;#39;, another:&amp;#39;anotherGetter&amp;#39;, ]) } }</pre>Mapping mutation

When mapping a mutation, you can use the following syntax to submit the mutation.

this.$store.commit(&#39;mutationName`)

For example:

import { mapMutations } from &#39;vuex&#39;

export default {
  methods: {
    ...mapMutations([
      &#39;search&#39;, // 映射 `this.increment()` 到 `this.$store.commit(&#39;search&#39;)`

      // `mapMutations` 也支持 payloads:
      &#39;searchBy&#39; // 映射 `this.incrementBy(amount)` 到 `this.$store.commit(&#39;searchBy&#39;, amount)`
    ]),
    ...mapMutations({
      find: &#39;search&#39; // 映射 `this.add()` 到 `this.$store.commit(&#39;search&#39;)`
    })
  }
}

Mapping action

Mapping action is very similar to mapping mutation in that it can also be done in a method. Using a mapper will bind

this.$store.dispatch('actionName')

to the name or key of the object in the mapper array. <pre class="brush:js;toolbar:false;">import { mapActions } from &amp;#39;vuex&amp;#39; export default { // ... methods: { ...mapActions([ &amp;#39;increment&amp;#39;, // 映射 `this.increment()` 到 `this.$store.dispatch(&amp;#39;increment&amp;#39;)` // `mapActions` 也支持 payloads: &amp;#39;incrementBy&amp;#39; // 映射 `this.incrementBy(amount)` 到 `this.$store.dispatch(&amp;#39;incrementBy&amp;#39;, amount)` ]), ...mapActions({ add: &amp;#39;increment&amp;#39; // 映射 `this.add()` 到 `this.$store.dispatch(&amp;#39;increment&amp;#39;)` }) } }</pre>Summary

After seeing this, you should be able to learn:

    How mapping in Vuex works and why you should use it With a deep understanding
  • Be able to map all components in the Vuex store (state, getter, mutation, action)
  • Know when you should map the store
English original address: https://blog.logrocket.com/a-complete-guide-to-mapping-in-vuex/

Author: Moses Anumadu

Related recommendations:


2020 front-end vue interview questions summary (with answers)

Vue tutorial recommendation: The latest 5 vue.js video tutorial selections in 2020

For more programming-related knowledge, please visit:
Introduction to Programming

! !

The above is the detailed content of The Complete Guide to Mapping in Vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete