首页 > 解决方案 > 计算数组在模板中不可用

问题描述

我希望我的数组在两个给定日期之间保存记录以始终反映选择的从日期到日期,但简单地在计算方法中从 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>

标签: vue.js

解决方案


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
  }
}

推荐阅读