vuex中 this.$store.dispatch() 与 this.$store.commit()

一、理解

this.$store.dispatch 分发 actions-> 调用 mutations->改变 states

二、思考

1、为什么不直接分发 mutation

mutation 有必须同步执行的限制,而 Action 不受约束,可以在 action 内部执行异步操作

2、Action 通常是异步的,如何知道 action 什么时候结束?如何才能组合多个 action,处理复杂的异步流程

store.dispatch 可以处理被触发的 action 的处理函数返回 Promise,并且 store.dispatch 仍旧返回 Promise

引用官网举例:

// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行

三、比较

1、相同点

都可以修改 state,并且也会触发视图的更新

2、 不同点

this.$store.dispatch() :含有异步操作,例如向后台提交数据,写法:this.$store.dispatch(‘action方法名’,值)
this.$store.commit():同步操作,,写法:this.$store.commit(‘mutations方法名’,值)

commit 调用的是 vuex 中 mutation 里的方法,存在同步限制;
dispatch 调用的数 vuex 中 action 里的方法,action 中可以调用 mutation 中的函数,也可执行异步操作;

commit:同步操作

// 存储
this.$store.commit('chgval',name);
// 取值
this.$store.state.chgval;

dispatch:异步操作

// 存储
this.$store.dispatch('listdata',name);
// 取值
this.$store.getters.listdata;

四、案例

Vuex文件 src/store/index.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  // state专门用来保存 共享的状态值
  state: {
    // 保存登录状态
    login: false
  },
  // mutations: 专门书写方法,用来更新 state 中的值
  mutations: {
    // 登录
    doLogin(state) {
      state.login = true;
    },
    // 退出
    doLogout(state) {
      state.login = false;
    }
  }
});

组件JS部分 : src/components/Header.vue

<script>
// 使用vux的 mapState需要引入
import { mapState } from "vuex";

export default {
  // 官方推荐: 给组件起个名字, 便于报错时的提示
  name: "Header",
  // 引入vuex 的 store 中的state值, 必须在计算属性中书写!
  computed: {
    // mapState辅助函数, 可以快速引入store中的值
    // 此处的login代表,  store文件中的 state 中的 login, 登录状态
    ...mapState(["login"])
  },
  methods: {
    logout() {
      this.$store.commit("doLogout");
    }
  }
};
</script>

组件JS部分 : src/components/Login.vue

<script>
export default {
  name: "Login",
  data() {
    return {
      uname: "",
      upwd: ""
    };
  },
  methods: {
    doLogin() {
      console.log(this.uname, this.upwd);
      let data={
        uname:this.uname,
        upwd:this.upwd
      }
       this.axios
        .post("user_login.php", data)
        .then(res => {
          console.log(res);
          let code = res.data.code;

          if (code == 1) {
            alert("恭喜您, 登录成功! 即将跳转到首页");

            // 路由跳转指定页面
            this.$router.push({ path: "/" });

            //更新 vuex 的 state的值, 必须通过 mutations 提供的方法才可以
            // 通过 commit('方法名') 就可以出发 mutations 中的指定方法
            this.$store.commit("doLogin");
          } else {
            alert("很遗憾, 登陆失败!");
          }
        })
        .catch(err => {
          console.error(err);
        });
    }

  }
};
</script>

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老电影故事

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值