疯狂的技术宅

以前出于工作目的,编写和翻译了大量的技术文章,以前端为主,删掉了过时的、毫无营养的内容,留下的都是精华。


  • 首页

  • 分类

  • 标签

  • 归档

  • 关于本站

  • 回到主站

  • 搜索

Vuex 映射完全指南

时间: 2020-09-10 分类: 前端技术   字数: 1226 字 阅读: 3分钟
标签: #vuex# #vue# #映射#
  • 本文译自:https://blog.logrocket.com/a-complete-guide-to-mapping-in-vuex/
  • 译者:疯狂的技术宅

Vuex 是一把双刃剑。如果使用得当,使用 Vue 可以使你的工作更加轻松。如果不小心,它也会使你的代码混乱不堪。

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

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

本文假设你了解 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
标签: #vuex# #vue# #映射#

标题:Vuex 映射完全指南

链接:https://fe-tech.viewnode.com/post/202009/10/

作者:疯狂的技术宅

声明: 本博客文章除特别声明外,均采用 CC BY-NC-ND 4.0 国际许可协议( 知识共享署名-非商业性使用-禁止演绎 4.0),转载请注明出处!

JavaScript 的 var,let 和 const 总结
面向对象与函数式编程的简单案例
  • 文章目录
  • 站点概览
疯狂的技术宅

疯狂的技术宅

退休程序员,硬件发烧友,人工智能爱好者。写写代码喝喝茶,晒晒太阳带带娃。

457 日志
8 分类
583 标签
GitHub
友情链接
  • viewnode
  • mofish
标签云
  • Javascript 172
  • Node.Js 62
  • Vue 36
  • Typescript 28
  • 实战项目 28
  • 面试 21
  • React 20
  • Css 17
  • 面试题 16
  • 教程 13
  • Promise 12
  • Chrome 9
  • Debug 9
  • 调试 9
  • 资源 9
  • Deno 8
  • Dom 8
  • 杂谈 8
  • 正则表达式 8
  • 测试 8
  • Vuex 中的映射是什么?
  • 映射 state
  • 何时映射整个 state
  • 映射 getter
  • 映射 mutation
  • 映射 action
  • 总结
© 2018 - 2022 疯狂的技术宅 All Rights Reserved
Powered by - Hugo v0.99.0 / Theme by - NexT
Storage by 俺的服务器 / 冀ICP备2022010157号
0%