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


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 的响应式系统的一部分缓存其中的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM