在vuex mapState中访问vue方法

时间:2018-12-23 12:25:13

标签: javascript vue.js vuex

在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
          }
        });
      }
    })
  }
};

1 个答案:

答案 0 :(得分:2)

当您将计算的props定义为函数时,

this绑定到组件的顶点。

来自docs

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