vuex多模块模式下使用辅助函数(开启了vuex的命名空间)

下面以mapGetters辅助函数为例
其它mapActions, mapMutations, mapState辅助函数声明和调用雷同

页面中声明和调用

<template>
  <div>VueX练习</div>
</template>
<script>
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
export default {
  name: 'Vuex',
  data () {
    return {}
  },
  computed: {
    /**
     * mapGetters对象形式(可以起别名) + 开启了命名空间(namespaced: true)
     * 需要带上模块名称才可以访问getters,例如下面的'common'模块名称
     * **/
    // 方式一(简洁),引入多个模块的getters时,则需要写多个mapGetters
    ...mapGetters('common', {
      doneTodos: 'doneTodos'
    })
    // 方式二(繁琐)
    // ...mapGetters({
    //   doneTodos: 'common/doneTodos'
    // })
  },
  mounted () {
    const that = this
    /**
     * 开启了命名空间(namespaced: true)
     * 如果不使用辅助函数,则需要带上模块名称才可以访问getters,例如下面的'common/doneTodos'
     * **/
    // console.log('that.$store.getters[\'common/doneTodos\']', that.$store.getters['common/doneTodos'])
    console.log('that.doneTodos', that.doneTodos)
  }
}
</script>
<style scoped></style>

vuex配置(多模块模式)

vuex总入口文件(index.js):

import Vue from 'vue'
import Vuex from 'vuex'
import common from './modules/common' // 引入common模块
Vue.use(Vuex)

export default new Vuex.Store({
  strict: true, // 严格模式
  modules: {
    common: common
  }
})

common模块如下:

const common = {
  namespaced: true, // 开启了命名空间(个人理解:需要写完整了调用路径才可以调用对应的vuex方法或者变量)
  state: () => ({
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  }),
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
}

export default common
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值