VueJs中的计算值-异步调用中的用法

时间:2019-12-03 15:39:17

标签: vue.js asynchronous nuxt.js

我正在.vue文件的computed:部分中创建一个动态数组。这个数组有一组我每个人都想调用的URL(在重复的组件中),以获取文章。这些文章各不相同,因此在页面渲染时将生成计算数组,完成后,我想在组件创建时调用url。

computed: {
    calcTheArray() {
        // make the actual array
        // basically, I grab a (computed! so can't use that in async either) 
        // array with months that have passed before today
        // I create an array with combined urls, that incorporate those month names
        // no other dependencies exist
        return array;
    }
}, 

然后:

async asyncData({ error, app, }) {
    try {
        // lots of things happen here, another api call, some parsing etc.

        const promises = [];
        this.calcTheArray.forEach((value) => {
            promises.push(app.$axios.$get(`${value}`, { useCache: true }));
        });
    } catch (e) {
        console.log(e);
        return error({ statusCode: 500, message: e.message });
    }
},

我得到的错误是:Cannot read property 'calcTheArray' of undefined

我有点理解为什么为什么,因为异步功能是...很好的异步方式,所以我的数据还不存在?我认为?但是,我该如何将动态创建的URL放入axios调用中?

到目前为止,我一直在尝试查看this.calcTheArray是否是罪魁祸首,并尝试使用不同的方式来使用计算所得的数组(例如,vm.calcTheArray,仅是calcTheArray),我是ve还尝试在data() {部分

中定义我的数组
data() {
    return {
      calcTheArray: [],
    };
  },

但是后来我(显然)以Duplicated key 'calcTheArray'结尾。

我很茫然。谁能给我指点?

1 个答案:

答案 0 :(得分:1)

如果我正确理解,您只想在calcTheArray实际上已计算出一些值并防止发生未定义的错误时才执行异步方法。在这种情况下,您可以使用观察程序来触发异步功能,您可以尝试以下操作:

computed: {
    calcTheArray() {
        // your code to create the array;
        return array;
    }
},
watch: {
    calcTheArray() {
        // executed when there's any mutation detected by vue on calcTheArray;
        this.asyncData(object)
    }
},
methods: {
    async asyncData({ error, app, }) {
      try {
         // lots of things happen here, another api call, some parsing etc.

         const promises = [];
         this.calcTheArray.forEach((value) => {
            promises.push(app.$axios.$get(`${value}`, { useCache: true }));
         });
       } catch (e) {
         console.log(e);
         return error({ statusCode: 500, message: e.message });
       }
   }
}

这样,vue将在启动异步方法之前等待计算所得的数组。希望它很适合您。