【问题标题】:Access vue method within vuex mapState在 vuex mapState 中访问 vue 方法
【发布时间】:2019-05-23 00:53:13
【问题描述】:

在 vuex mapState 中计算数据时,我有一项重要任务要做。每次更改数据时都需要调用这个vue方法countAlerts;为此,计算属性需要调用该方法,但 this 作用域在使用洞察 vuex mapState 时没有 vue 方法。

export default {
  name: "Alerts",
  methods: {
    countAlerts(data, period) {
      /// DO SOMETHING, THEN RETURN DATA
      return data;
    }
  },
  computed: {
    ...mapState({
      foundation: state => state.insights.foundation,
      insights: state => {
        return state.insights.list.filter(al => {
          switch (state.insights.foundation.period) {
            case "daily":
               // ====>> NEED TO CALL METHOD HERE <<=====
              al = this.countAlerts(al, "daily");
              if (
                al.threeDayUp ||
                al.threeDayDown ||
                al.greatDayUp ||
                al.greatDayDown
              ) {
                return al;
              }
              break;
            ///  MORE CODE ABOVE
          }
        });
      }
    })
  }
};

【问题讨论】:

  • 不要使用箭头功能,它会限制范围,您无法访问this。 Amade 回答正确。
  • 我注意到了。我来自角度/打字稿。我已经很习惯了……

标签: javascript vue.js vuex


【解决方案1】:

this 在您将计算道具定义为函数时绑定到组件的上下文。

来自docs

// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
  return state.count + this.localCount
}

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 2021-10-20
    • 2020-08-13
    • 2021-10-19
    • 2021-11-05
    • 2020-05-04
    • 2019-11-30
    • 2020-06-14
    相关资源
    最近更新 更多