在 vuex mapState 中访问 vue 方法

cal*_*res 2 javascript vue.js vuex

在 vuex mapState 中计算数据时,我有一项重要的任务要做。countAlerts每次数据改变时我都需要调用这个vue方法;要做到这一点,计算属性需要调用该方法,但this在使用 Insight 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
          }
        });
      }
    })
  }
};
Run Code Online (Sandbox Code Playgroud)

Ama*_*ade 5

this 当您将计算的 props 定义为函数时,它绑定到组件的上下文。

文档

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