【问题标题】:Computed value in VueJs - usage in asynch callVue Js 中的计算值 - 异步调用中的用法
【发布时间】:2020-03-28 08:15:00
【问题描述】:

我正在我的 .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)我还尝试定义我的data() { 部分中的数组

data() {
    return {
      calcTheArray: [],
    };
  },

但是我(显然)最终得到了Duplicated key 'calcTheArray'

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

【问题讨论】:

  • 假设这是 Nuxt,请参阅 nuxtjs.org/guide/async-data。引用'您确实可以通过asyncData 内的this 访问组件实例,因为它是在启动组件之前调用的。'。在不知道 calcTheArray 依赖什么的情况下,很难提供进一步的建议。
  • 谢谢!你是对的,我正在使用 Nuxt。 calcTheArray 仅取决于今天的日期(或更准确地说是月份)。从起点到本月的所有过去几个月,我都有不同的 API 调用要做。我从一组月份名称中动态构建它们。这几乎就是calcTheArray 所做的一切。我现在明白为什么我不能在异步中使用calcTheArray,但我仍然不清楚我应该做什么来让调用正常工作......
  • 您不能将代码从calcTheArray 移到您的asyncData 函数中吗?
  • 我刚刚更新了我的代码...我引用的数组也是计算出来的...
  • 那么所有相关计算属性的最终依赖关系是什么?例如他们是否依赖任何道具等?实例中是否有任何您需要的内容,或者您​​是否只是为了方便而使用了计算属性?有什么理由不能将它们定义为普通的 JavaScript 函数,与您的 Vue 组件选项完全分开?

标签: vue.js asynchronous nuxt.js


【解决方案1】:

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

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 将在启动异步方法之前等待计算数组。希望它适合你。

【讨论】:

  • 这看起来很合乎逻辑......对于我的情况,不需要实际观看,因为文章将在页面加载时加载,但我确实从您的回答中获得了一些见解。谢谢!
猜你喜欢
  • 2020-08-23
  • 2019-08-07
  • 1970-01-01
  • 2018-02-18
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
相关资源
最近更新 更多