【问题标题】:Vue js .bind does not work while passing callback to vuex storeVue js .bind 在将回调传递给 vuex 商店时不起作用
【发布时间】:2020-06-30 15:23:50
【问题描述】:

当我将redirectCallback 传递给 vuex 商店时,这有效:

  var router = this.$router;
  var redirectCallback = () => {
    return userApi.deleteContact(userId, contactId).then(res => {
      store.commit("modals/HIDE_DANGER_MODAL");
      if (!res) {
        // error occurred
        return store.commit("modals/SHOW_DRROR_MODAL", {
          modalTitle: "Failed",
          modalBody: "Couldn't delete contact"
        });
      }
      store.commit("modals/SET_CUSTOM_CLOSE_OPERATION", function() {
        router.replace("/contacts");
      });
      return store.commit("modals/SHOW_SUCCESS_MODAL", {
        modalTitle: "Success",
        modalBody: "Contact Deleted Successfully!"
      });
    });
  };

但如果我这样做,它不起作用,我得到错误cannot read property .replace of undefined

  var redirectCallback = () => {
    return userApi.deleteContact(userId, contactId).then(res => {
      store.commit("modals/HIDE_DANGER_MODAL");
      if (!res) {
        // error occurred
        return store.commit("modals/SHOW_DRROR_MODAL", {
          modalTitle: "Failed",
          modalBody: "Couldn't delete contact"
        });
      }
      store.commit("modals/SET_CUSTOM_CLOSE_OPERATION", function() {
        this.$router.replace("/contacts");
      });
      return store.commit("modals/SHOW_SUCCESS_MODAL", {
        modalTitle: "Success",
        modalBody: "Contact Deleted Successfully!"
      });
    });
  };

我刚刚在 vue 组件方法中使用了 this.$router 而不是局部变量,它不起作用。 这是我将回调传递给 vuex 商店的方法:

  store.commit(
    "modals/SET_DANGEROUS_OPERATION",
    redirectCallback.bind(this)
  );

这是我调用回调的方式:

  await store.dispatch("modals/performDangerousOperation");

简而言之,我只是调度调用回调(承诺)的“performDangerousOperation”,然后它显示另一个模式。该模式有一个关闭按钮,可以触发“performCustomCloseOperation”(我们在上面的 redirectCallback 中设置)。

我只是想知道为什么.bind 在这里不起作用(由于 this.$router 没有定义)?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    这是因为匿名函数创建了另一个this,它覆盖了redirectCallback中的this

      store.commit("modals/SET_CUSTOM_CLOSE_OPERATION", function() {
        this.$router.replace("/contacts");
      });
    

    将其更改为箭头函数应该可以工作:

      store.commit("modals/SET_CUSTOM_CLOSE_OPERATION", () => {
        this.$router.replace("/contacts");
      });
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2017-12-18
      • 2021-05-27
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 2020-01-10
      • 2019-08-18
      相关资源
      最近更新 更多