Home > Enterprise >  Accessing variables between methods Vue
Accessing variables between methods Vue

Time:08-18

I have a method does performs two API calls and stores them both in separate variables. I would like to be able to access those variables from another method in order to manipulate the data.

How can I access the data from another method in Vue.

Here is my api call:

 async apiCall () {
    const [result1, result2] = 
    await Promise.all([
      get('lots/inputsOutputs', { locationId: '56464589a6d3b', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }),
      get('lots/inputsOutputs', { locationId: '5464564563ebd', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') })
    ]);
    this.Loading = false;
    return [result1, result2];
  }

CodePudding user response:

Firstly, of course you can call the function in your desired function to return the variables first and using the await to wait for the promise to finish first.

async apiCall () {
    const [result1, result2] = 
    await Promise.all([
      get('lots/inputsOutputs', { locationId: '56464589a6d3b', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }),
      get('lots/inputsOutputs', { locationId: '5464564563ebd', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') })
    ]);
    this.Loading = false;
    return [result1, result2];
  },
  async myFunction() {
    const [result1, result2] = await apiCall(); 
    // enter code here
  }

If the function is in the same component, you can use the data to store the results. Alternatively, you may also use Vuex and/or LocalStorage to store them or using the EventBus, but they may be a bit of overkill.

CodePudding user response:

Did you try to set result1 and result2 as data property (like Loading)? Then You don't need return from your apiCall function, just set data properties:

data() {
  result1: [],
  result2: [],
  Loading: false
},
methods: {
  async apiCall () {
    [this.result1, this.result2] = await Promise.all([
      get('lots/inputsOutputs', { locationId: '56464589a6d3b', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }),
      get('lots/inputsOutputs', { locationId: '5464564563ebd', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') })
    ]);
    this.Loading = false;
  }
}
  • Related