Vuex 映射指南

做者:Moses Anumadu

翻译:疯狂的技术宅前端

原文:https://blog.logrocket.com/a-...vue

未经容许严禁转载程序员

Vuex 是一把双刃剑。若是使用得当,使用 Vue 可使你的工做更加轻松。若是不当心,它也会使你的代码混乱不堪。面试

使用 Vuex 以前,你应该先了解四个主要概念:state、getter、mutation 和 action。一个简单的 Vuex 状态在 store 中的这些概念中操做数据。 Vuex 中的映射提供了一种从中检索数据的好方法。vuex

在文中,我将演示如何映射 Vuex 存储中的数据。若是你熟悉 Vuex 基础,那么这些内容将会帮你编写更简洁、更便于维护的代码。segmentfault

本文假设你了解 Vue.js 和 Vuex 的基础知识。数组

Vuex 中的映射是什么?

Vuex 中的映射使你能够将 state 中的任何一种属性(state、getter、mutation 和 action)绑定到组件中的计算属性,并直接使用 state 中的数据。服务器

下面是一个简单的 Vuex store 例子,其中测试数据位于 state 中。微信

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

Vue.use(Vuex)

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

若是要从 state 中访问 data 的值,则能够在 Vue.js 组件中执行如下操做。多线程

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

上面的代码能够工做,可是随着 state 数据量的开始增加,很快就会变得很难看。

例如:

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: {},
    }
  }
})

要从处于 state 中的用户对象获取用户名:

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

这样能够完成工做,可是还有更好的方法。

映射 state

要将 state 映射到 Vue.js 组件中的计算属性,能够运行如下命令。

import { mapGetters } from 'vuex';

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

如今你能够访问组件中的整个用户对象。

你还能够作更多的事,例如把对象从 state 添加到 mapState 方法。

import { mapGetters } from 'vuex';

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

如你所见,这要干净得多。能够经过如下方式轻松访问用户名:

{{user.data.name}}

services 对象和映射的许多其余的值也是如此。

你注意到咱们是如何将数组传递给 mapState() 的吗?若是须要为值指定其余名称,则能够传入一个对象。

import { mapGetters } from 'vuex';

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

如今能够经过简单地调用 userDetails 来引用 user

什么时候映射整个 state

根据经验,仅当 state 中有大量数据,而且组件中所有须要它们时,才应该映射。

在上面的例子中,若是咱们只须要一个值(例如 username),则映射整个用户对象就没有多大意义。

在映射时,整个对象将会所有加载到内存中。实际上咱们并不想继续把不须要的数据加载到内存中,由于这将是多余的,而且从长远来看会影响性能。

映射 getter

映射 getter 的语法与 mapState 函数类似。

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'firstCount',
      'anotherGetter',
    ])
  }
}

与映射 state 相似,若是你打算使用其余名称,则能够把对象传递给 mapGetters 函数。

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters([
      first:'firstCount',
      another:'anotherGetter',
    ])
  }
}

映射 mutation

映射 Mutation 时,能够在用如下语法来提交 Mutation。

this.$store.commit('mutationName`)

例如:

import { mapMutations } from 'vuex'

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

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

映射 action

映射 action 与映射 mutation 很是类似,由于它也能够在方法中完成。使用映射器会把 this.$store.dispatch('actionName') 绑定到映射器数组中的名称或对象的键。

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 映射 `this.increment()` 到 `this.$store.dispatch('increment')`

      // `mapActions` 也支持 payloads:
      'incrementBy' // 映射 `this.incrementBy(amount)` 到 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 映射 `this.add()` 到 `this.$store.dispatch('increment')`
    })
  }
}

总结

看到这里,你应该可以学到:

  • 对 Vuex 中的映射是如何工做的以及为何要使用它有了深入的了解
  • 可以映射 Vuex store 中的全部组件(state、 getter、 mutation、action)
  • 知道何时应该映射 store

173382ede7319973.gif


本文首发微信公众号:前端先锋

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎扫描二维码关注公众号,天天都给你推送新鲜的前端技术文章

欢迎继续阅读本专栏其它高赞文章:


相关文章
相关标签/搜索