![](/img/trans.png)
[英]“TypeError: Cannot read property '$emit' of undefined” - VueJS
[英]TypeError: Cannot read property '$http' of undefined - VUEJS
我無法在過濾器中訪問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;
});
引用 Vue.js 文檔:
Vue.js 允許您定義可用於應用常見文本格式的過濾器。
Vue.js 過濾器無法訪問this
,因為它們是純函數。 這意味着您不能在過濾器內使用任何注入。
此外,過濾器必須是同步的,這意味着您不能在其中進行 HTTP 調用或任何異步調用。
過濾器通常用於格式化文本值,如貨幣、數字、日期或其他常見的可呈現信息。
要解決您的問題,您也不能使用computed
。 因為它們也必須是同步的,所以你只剩下methods
了。 但是您也不能只在模板中調用異步方法,因此您應該在顯示數據之前先 map 您的數據。 您可以在mounted
或created
的生命周期方法中進行映射。
編輯:添加示例
我覺得您的模板中發生了很多事情,我建議您將迭代項拆分為一個組件,我們稱之為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>
你真的應該首先考慮組件,而不是接觸filters
或directives
等更小的東西,通常components
是你需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.