neuron
neuron

Reputation: 21

Use exported value in setup of Vue Composition API

In a plain js file the code looks like

export default async function exportData() {
  const { data } = await store
      .dispatch('fetchData')

  const { bookings } = data
  const booking = bookings.length ? bookings[0]._id : ''

  const event = {
    bookingID: booking
  }

  // other methods and variables

  return {
    .....
  }
}

inside the vue file

import exportData from './exportData'
export default {
  setup() {
    const {
      fetchEvents,
      isEventActive,
    } = exportData()
    fetchEvents()
  }
}

the problem is in vue components the values from exportData gets undefined, gets error fetchEvents is not a function when the export is asynchronous. works well if not asynchronous. what is the workaround here??

Upvotes: 2

Views: 1456

Answers (1)

Atif Zia
Atif Zia

Reputation: 793

You can try to declare fetchEvents,isEventActive methods in plan js file without wrapping it inside any function

const fetchEvents = () => {
   //body
};

const isEventActive = () => {
     //body
};

and export them as

export {fetchEvents, isEventActive};

now use them

import {fetchEvents,isEventActive} from 'path-to-js-file'
export default {
  setup() {
    fetchEvents()
    isEventActive()
  }
}

Upvotes: 1

Related Questions