Home > OS >  access global script function vue
access global script function vue

Time:01-27

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 ? Meanwhile using Window object (alike window.fakeApiRequest ) is useless also.

CodePudding user response:

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>

CodePudding user response:

Welcome to stackoverflow,

the first thing that came to my mind was if it is really needed to do that many api requests. 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?

I think in your example, that you posted into the codesandbox the problem is, that you don’t set the new array. The call to [].forEach is not setting anything. As you call an api, you need to make sure, all requests are resolved.

As some of the requests might be rejected, you could await Promise.allSettled and filter the results by the status:

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)
    }
  },
};
  • Related