简体   繁体   English

访问全局脚本 function vue

[英]access global script function vue

How如何

 <script> const fakeApiRequest = (id) => { return id; }; export default { data() { return { ids: [1, 2, 3, 4, 5, 6], }; }, methods: { newValues(id) { this.ids.forEach((el) => el.fakeApiRequest(id)); } }, }; </script>

How can I access global script function - const fakeApiRequest?如何访问全局脚本 function - const fakeApiRequest? Meanwhile using Window object (alike window.fakeApiRequest ) is useless also.同时使用 Window object (类似于 window.fakeApiRequest )也没有用。

Welcome to stackoverflow,欢迎来到计算器,

the first thing that came to my mind was if it is really needed to do that many api requests.我首先想到的是是否真的需要执行那么多 api 请求。 Just a side note: wouldn't it be better to receive the data for multiple ids at the same time with only one API call?附带说明:仅通过一次 API 调用同时接收多个 ID 的数据不是更好吗?

I think in your example, that you posted into the codesandbox the problem is, that you don't set the new array.我认为在你的例子中,你发布到 codesandbox 的问题是,你没有设置新数组。 The call to [].forEach is not setting anything.[].forEach的调用未设置任何内容。 As you call an api, you need to make sure, all requests are resolved.当您拨打 api 时,您需要确保所有请求都已解决。

As some of the requests might be rejected, you could await Promise.allSettled and filter the results by the status:由于某些请求可能会被拒绝,您可以等待Promise.allSettled并按状态过滤结果:

const fakeApiRequest = async (id) => {
  // await some api call...
  return id;
};

export default {
  methods: {
    async newSuccessIds() {
      const results = await Promise.allSettled(
        // the fakeApiRequest can be called directly
        // as it is part of the closure context.
        this.ids.map(fakeApiRequest)
      );

      return results
        .filter(({ status }) => status === 'fulfilled')
        .map(({ value }) => value)
    }
  },
};

You can try something like this:你可以尝试这样的事情:

<script>
export default {
  data() {
    return {
     ids: [1, 2, 3, 4, 5, 6],
    };
  },
  
  methods: {
    fakeApiRequest(id){
      return id 
    },
    newValues(id) { 
      this.ids.forEach((element) => {
        console.log(this.fakeApiRequest(element))
      });
    }
  },
};
</script>

<template>
    <div>
    {{newValues(5)}}
  </div>
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM