vue.js - 计算数组在模板中不可用
问题描述
我希望我的数组在两个给定日期之间保存记录以始终反映选择的从日期到日期,但简单地在计算方法中从 Axios 返回 response.data 似乎并不能解决问题。如何获取计算方法以将结果提供给应用程序?
<template>
<div>
<p v-for="event in events">{{event.title}}</p>
</div>
</template>
<script>
export default {
name: "App",
data () {
return {}
},
computed: {
fromDate: function() { ..code.. },
toDate: function() { ..code.. },
events: function() {
axios.get('json/' + this.fromDate + '/' + this.toDate).then(response => {
return response.data;
});
}
}
}
</script>
解决方案
events: function() {
axios.get('json/' + this.fromDate + '/' + this.toDate)
.then(response => {
return response.data;
});
}
首先,您并没有真正在该函数中返回任何内容。为了实现这一点,您可以使用名为vue -async-computed的插件
// ...
import AsyncComputed from 'vue-async-computed'
// ...
Vue.use(AsyncComputed)
// ...
asyncComputed: {
events: function() {
return axios.get('json/' + this.fromDate + '/' + this.toDate)
.then(response => {
return response.data;
});
}
}
vue-async-computed
与 ES7 一起使用也可以:
asyncComputed: {
async events() {
const response = await axios.get('json/' + this.fromDate + '/' + this.toDate)
return response.data
}
}
推荐阅读
- javascript - 存储在对象中时如何从模板文字中删除空格?
- react-native - React-Native:Azure Pipelines 中的任务失败,但在本地却没有
- java - 如何在 Exo Player 中使用查询参数?
- c# - Razor Pages 链接基于当前页面错误呈现
- angular - 为什么我的 SafeResourceUrl 在同一类的方法中未定义
- javascript - JS:如何删除“垃圾邮件隐形字符”?
- bad-request - 为什么我只使用日期时间收到错误 400 错误请求
- c++ - C++ const 方法返回非 const 指针
- machine-learning - 我们能否指定在 Vowpal Wabbit 中使用哪种算法(例如,决策树、SVM、集成、NN)?或者,Automl 是否选择算法本身?
- python - 将 pandas 数据帧传递给 FastAPI 用于 NLP ML