简体   繁体   中英

Importing a async function ES6 vuejs and TypeScript

I'm trying to make my code a bit more reusable, and as such, I want to store multiple async functions into another file.

blog.ts


import db from '@/firebase/init'

async function getTags (uid) {
  const tags = db.collection('tags').where('blogId', '==', uid)
  const data = []
  await tags.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
        data.push(doc.data().tag)
      })
      return data
    })
    .catch(err => {
      console.log('Error getting documents', err)
    })
}

export default getTags

anotherpage.vue

<script>
import { getTags } from '@/functions/blog'

  mounted () {
    if (this.$route.params.blog) {
      this.blog = this.$route.params.blog
    }
    getTags(this.blog.uid)
}

Returns with the error that

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Object(...) is not a function"

found in

---> <EditBlog> at src/components/admin/admin/Blog/EditBlog.vue
       <CreateBlog> at src/components/admin/admin/Blog/CreateBlog.vue
         <LayoutDefault> at src/App.vue
           <Root>

Can anyone point me in the direction of a guide of how to correctly import these functions?

You're trying to use a named import when you import but are making the module as a default export. To fix this, you can just import getTags from '@/functions/blog' .

Technically getTags is not a Named export, it's the default export. If you're planning to have a bunch of functions in one file, and want to use named exports/imports you just have to remove the default from your function. Now you will be able to pick and choose what to import since they are named exports! There's a simple blog post that goes over this pretty quickly here

This is how your file(blog.ts) with multiple named exports (with your functions) would look like.

export async function getTags (uid) {
  const tags = db.collection('tags').where('blogId', '==', uid)
  const data = []
  await tags.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
        data.push(doc.data().tag)
      })
      return data
    })
    .catch(err => {
      console.log('Error getting documents', err)
    })
}

export async function getLaundry(uid) {
  //stuff
}

Then in your file that you want to import just the ones you want, let's say you just want getLaundry you can do so like:

import { getLaundry } from '@/functions/blog'

Or both like:

import { getLaundry, getTags } from '@/functions/blog'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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