【问题标题】:TypeError: Cannot read property '$http' of undefined - VUEJSTypeError:无法读取未定义的属性'$http' - VUEJS
【发布时间】:2019-11-10 15:17:22
【问题描述】:

我无法在过滤器中访问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;
});

【问题讨论】:

  • 我认为这个解决方案是正确的,但我是 vuejs 的新手,我正在使用单页应用程序,所以我没有使用这个解决方案,但感谢您的帮助 :)

标签: javascript arrays vue.js


【解决方案1】:

引用 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 是您需要的。

【讨论】:

  • 谢谢你的帮助,我明白了,你能给我举个例子吗?
  • 我为您添加了一个示例,您可能想更改一些内容。
猜你喜欢
  • 2021-12-08
  • 2020-11-08
  • 2017-09-16
  • 2020-08-27
  • 2021-12-28
  • 1970-01-01
  • 2019-05-16
  • 2019-11-26
  • 2020-11-23
相关资源
最近更新 更多