vue3.x专题十一 ---- vuex使用方法总结二(分模块状态)

1、分模块状态使用vuex(store/index.js):

import { createStore } from 'vuex'
// 模块A
const moduleA = {
  state: () => {
    return {
      username: 'moduleA'
    }
  },
  mutations: {

  },
  actions: {

  },
  getters: {

  }
}
// 模块B
const moduleB = {
  namespaced: true,
  state: () => {
    return {
      username: 'moduleB'
    }
  },
  mutations: {
    updateName (state) {
      state.username = 'mutations B新名字'
    }
  },
  actions: {
    // 异步操作:请求数据函数
    updateName (context) {
      // 发请求
      setTimeout(() => {
        context.commit('updateName', 'actions B新名字')
      }, 1000)
    }

  },
  getters: {
    newName (state) {
      return state.username + 'B模块'
    }
  }
}

// 创建vuex仓库并导出
export default createStore({
  state: {
   
  },
  mutations: {
 
  },
  actions: {

  },
  modules: {
    // 分模块
    moduleA,
    moduleB
  },
  getters: {
  }
})

2、在组件中使用分模块的vuex数据

<template>
  <h3>使用子模块的数据:</h3>
  <div>
   moduleA的state模块的username: {{ $store.state.moduleA.username }}
  </div>

  <div>
   moduleB的state模块的username: {{ $store.state.moduleB.username }}
  </div>
  <br>
  <br>
  <br>
  <div>
    <button @click="mutationsBFn">mutationsBFn改名字</button>
  </div>
  <br/>
  <br/>
  <div>
    <button @click="actionsBFn">actionsBFn改名字</button>
  </div>

</template>
<script>
import { useStore } from 'vuex'
export default {
  name: 'App',
  setup (props) {
    const store = useStore()
    const mutationsBFn = () => {
      store.commit('moduleB/updateName', 'mutationsBFn')
    }
    const actionsBFn = () => {
      store.dispatch('moduleB/updateName', { test: 'test' })
    }
    return {
      mutationsBFn,
      actionsBFn
    }
  }
}
</script>
<style lang="less">

</style>

这里总结一下modules (分模块)存在的两种情况:

  1. 默认的模块( 不带命名空间 ) : 在组件或者js文件中取值或者调用对应方法时,state 区分模块,其他 getters mutations actions 都在全局(通俗讲就是不带命名空间子模块定义的state数据,即时变量名和全局state中定义的变量名相同,也可以通过模块名取到对应的值,例如:$store.state.模块名.变量名),但是 getters ,mutations, actions中定义的方法或属性如果跟全局中定义的相同,那么取到的是全局的
  2. 带命名空间 namespaced: true 的模块:所有功能区分模块,更高封装度和复用(同名变量或者方法,可以在多个模块中使用)。

觉得有用的朋友,可以点赞评论收藏一哈。。。

  • 12
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值