首页 > 其他 > 详细

【Vuex】在vue组件中访问vuex模块中的getters/action/state

时间:2021-02-05 12:59:55      阅读:21      评论:0      收藏:0      [点我收藏+]

store的结构:

技术分享图片 

 city模块:

技术分享图片 

 在各模块使用了命名空间的情况下,即 namespaced: true 时:

组件中访问模块里的state

传统方法:

this.$store.state[‘模块名‘][‘属性名‘]

例如:this.$store.state.city.list。

控制台输出 this.$store.state

技术分享图片 

 mapState方法:

import { mapState } from ‘vuex‘
computed: {
    // ...
    ...mapState({
      list: state => state.city.list
    })
  }

组件中dispatch模块里的actions

传统方法:

// @params:opts Object or String 
this.$store.dispatch(‘模块名/属性名‘, opts)

组件中使用如:this.$store.dispatch(‘city/add‘, ‘上海‘)

mapActions方法:

引入:import { mapActions } from ‘vuex‘

技术分享图片

 methods中的属性名可以更改成其他任意名字,但是属性值需要和模块名,actions属性名对应。

在组件中访问模块里的getter

传统方法:

this.$store.getters[‘模块名/属性名‘]

如:this.$store.getters[‘city/findOne‘](‘a‘)

mapGetters方法:

引入:import { mapGetters } from ‘vuex‘

技术分享图片

这个getter返回的是一个函数,这样可以给getter传参。此时getter通过方法访问时,每次都会去进行调用,而不会缓存结果。

而getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

转自:https://www.cnblogs.com/caimuguodexiaohongmao/p/11854228.html

【Vuex】在vue组件中访问vuex模块中的getters/action/state

原文:https://www.cnblogs.com/vickylinj/p/14376757.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!