TypeError:无法读取未定义的属性'$ http'-VUEJS

时间:2019-11-10 15:17:22

标签: javascript arrays vue.js

我无法访问过滤器中的this.$http

<v-sheet height="500">
  <v-calendar :now="today" :value="today">
    <template v-slot:day="{ date }">
      <template v-for="event in eventsMap[date]">
        <v-menu :key="event.Ref" full-width offset-x>
          <template v-slot:activator="{ on }">
            <div v-ripple v-  v-on="on" >{{event | searchActivity}}</div>                    
          </template>
        </v-menu>
      </template>
    </template>
  </v-calendar>
</v-sheet>

这是我的JavaScript代码:

import Vue from "vue";
Vue.filter("searchActivity", function(val) {
  var params = {
    ProblemsID: val.ActivityRef
  };
  this.$http
    .post(auth.API_URL + "api/Problems/Activity", params, {
      headers: {
        Authorization: "Bearer " + auth.getAuthHeader()
      }
    })
    .then(
      response => {
        this.activityList = response.body;
      },
      response => {
        if (response.Status === true) {
          this.text1 = response.body.ResponseMessage;
          this.snackbar = true;
        } else {
          this.text1 = response.statusText;
          this.snackbar = true;
        }
      }
    );
  this.Obj = this.activityList.ActivityName;

  return this.Obj;
});

1 个答案:

答案 0 :(得分:0)

要引用Vue.js文档:

  

Vue.js允许您定义可用于应用常见文本格式的过滤器。

Vue.js过滤器无权访问this,因为它们是纯函数。这意味着您不能在过滤器内部使用任何注入。

此外,过滤器必须是同步的,这意味着您无法进行HTTP调用或其中的任何异步操作。

过滤器通常用于格式化文本值,例如货币,数字,日期或其他常见的可表示信息。

要解决您的问题,您也不能使用computed。因为它们也必须是同步的,所以只剩下methods。但是您也不能只在模板中调用异步方法,因此在显示数据之前应先映射数据。您可以在mountedcreated生命周期方法中进行映射。

编辑:添加了示例

我觉得您的模板中发生了很多事情,建议您将迭代项拆分为一个组件,我们将其称为EventDayView

<template>
  <v-menu :key="event.Ref" full-width offset-x>
    <template v-slot:activator="{ on }">
      <div v-ripple v-on="on">{{ activityList.ActivityName }}</div>                    
    </template>
  </v-menu>
</template>

<script>
export default {
  name: 'EventsDayView',
  props: {
    event: { type: Object, required: true }
  },
  data: () => ({
    activityList: null
  }),
  methods: {
    searchActivity (val) {
      // Your search activity API call
    }
  },
  mounted() {
    this.searchActivity(this.event).then(response => {
      this.activityList = response.body;
    });
  }
};
</script>

以后您可以像这样使用它:

<v-sheet height="500">
  <v-calendar :now="today" :value="today">
    <template v-slot:day="{ date }">
      <template v-for="event in eventsMap[date]">
        <EventDayView :key="event.Ref" :event="event" />
      </template>
    </template>
  </v-calendar>
</v-sheet>

您真正应该首先考虑组件,而不是接触小型filtersdirectives这样的东西,通常components是您所需要的。