【Vue】获取模块内的state数据

目标:

掌握模块中 state 的访问语法

尽管已经分模块了,但其实子模块的状态,还是会挂到根级别的 state 中,属性名就是模块名

68342784166


使用模块中的数据

  1. 直接通过模块名访问 $store.state.模块名.xxx

  2. 通过 mapState 映射:

    1. 默认根级别的映射 mapState([ ‘xxx’ ])

    2. 子模块的映射 :mapState(‘模块名’, [‘xxx’]) - 需要开启命名空间 namespaced:true

      注意namespaced后面有d!!!

      配好之后,模块名后面可以看见namespace的标志

      image-20240205164233329

      但是它可能有缓存,可以ctrl+F5强制刷新一下

modules/user.js

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  },
  myMsg: '我的数据'
}

const mutations = {
  updateMsg (state, msg) {
    state.myMsg = msg
  }
}

const actions = {}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

代码示例

$store直接访问

$store.state.user.userInfo.name

mapState辅助函数访问

...mapState(['count', 'title']),
// 写多个是完全没关系的,只要是不重名,互相之间是不冲突的,只是在加多个计算属性而已
...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),

访问

<!-- 访问模块中的state -->
<div>{{ user.userInfo.name }}</div>
<div>{{ setting.theme }}</div>
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 2中,你可以通过以下几种方式来修改storestate数据: 1. 使用mutations:mutations是用于修改state的方法。你可以在store的mutations对象中定义一个方法来修改state数据。例如: ```javascript // 在store中定义mutations const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }) // 在组件中调用mutations方法来修改state this.$store.commit('increment') ``` 2. 使用actions:actions用于处理异步操作,并且可以通过commit方法来调用mutations来修改state数据。例如: ```javascript // 在store中定义actions const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment') }, 1000) } } }) // 在组件中调用actions方法来修改state this.$store.dispatch('incrementAsync') ``` 3. 使用getters:getters用于对state进行过滤或计算。你可以在store的getters对象中定义一个方法来获取state数据,然后在组件中通过$store.getters来获取计算后的数据。例如: ```javascript // 在store中定义getters const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, getters: { doubleCount(state) { return state.count * 2 } } }) // 在组件中获取计算后的数据 this.$store.getters.doubleCount ``` 这些方法可以帮助你在Vue 2中修改storestate数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值