vuex-actions与vuex-modules

vuex-actions

  1. 在使用vuex时,有时需要使用异步操作,但是在mutations中是不支持异步操作的,这是就需要使用actions属性了
  2. actions属性的使用方法与mutations类似,都是形式为函数形式,不同的是actions属性的默认参数为context,还可以添加其他的参数,使用payload来表示,类型为对象类型
 actions: {
    actUpdateInfo(context, payload) {
        setTimeout(() => {
          context.commit('updateInfo');
        }, 1000);
        console.log(payload);
    }
  }
  1. 需要注意的是,对actions进行操作时,为了能够实现vuex对数据的追踪,必须在actions中使用mutations来对数据进行修改
  2. 在组件中调用该actions属性时使用dispatch()函数。
this.$store.dispatch('actUpdateInfo', '显示内容:');
  1. 为了实现对state进行修改后的提示操作,使用Promise来进行信息的打印。对actions进行修改,返回值为Promise对象
    actUpdateInfo(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          context.commit('updateInfo');
        }, 1000);
        console.log(payload);
        resolve('使用Promise进行actions操作');
      });
    }
  1. 在组件中对actions函数进行操作,由于返回值为Promise对象,使用then方法进行相应的操作,打印相关信息
      update() {
        this.$store.dispatch('actUpdateInfo', '显示内容:')
          .then(res => {
            console.log(res);
            console.log('操作成功');
          });
      }

在这里插入图片描述

vuex-modules

  1. modules属性代表的是模块。当项目过于复杂,通过对项目进行划分,分成几个模块方便管理。modules与store结构类似,有state、mutations、getters、actions等属性
const moduleA = {
  state: {},
  mutations: {},
  actions: {},
  getters: {}
}

  modules: {
    a: moduleA
  }
  1. 在模块中使用state属性时,与store中一致。不同的是,在组件中调用state中的属性时需要添加模块名,格式为:$store.state.a.属性名
<h2>{{$store.state.a.name}}</h2>
  1. mutations属性与store完全一致,需要注意的是,定义mutations时函数名不能与store中mutations中函数名称重复
  2. getters属性与在store中类似。在定义getters函数的时候,默认参数为state,还可以将getters属性作为参数传入。不同的是,在模块中的getters属性可以传入第三个参数“rootState”,该参数为store对象中的state属性,可以调用根对象中的state属性
  getters: {
    fullName(state) {
      return state.name + '0000';
    },
    fullName2(state, getters) {
      return getters.fullName + '1111';
    },
    fullName3(state, getters, rootState) {
      return getters.fullName2 + rootState.message;
    }
  }
    <h2>{{$store.getters.fullName}}</h2>
    <h2>{{$store.getters.fullName2}}</h2>
    <h2>{{$store.getters.fullName3}}</h2>
  1. actions属性与store中完全一致。不同的是actions中的参数context代表上下文,可以引用“rootState”与“rootGetters”,分别代表根中的state属性与getters属性,也就是store对象中的state属性与getters属性
  actions: {
    actUpdateName(context) {
      console.log(context.rootState);
      console.log(context.rootGetters);
      setTimeout(() => {
        context.commit('updateName', 'Name');
      }, 1000);
    }
  }

      actUpdateName() {
        this.$store.dispatch('actUpdateName');
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值