【问题标题】:Use exported value in setup of Vue Composition API在设置 Vue Composition API 时使用导出的值
【发布时间】:2021-08-13 20:55:53
【问题描述】:

在一个普通的 js 文件中,代码如下所示

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 {
    .....
  }
}

vue 文件内部

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

问题出在 vue 组件中,exportData 中的值未定义,当导出为异步时,出现错误 fetchEvents is not a function。如果不是异步的,效果很好。这里有什么解决方法??

【问题讨论】:

    标签: javascript vue.js vuejs2 async-await


    【解决方案1】:

    您可以尝试在计划 js 文件中声明 fetchEvents,isEventActive 方法,而无需将其包装在任何函数中

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

    并将它们导出为

    export {fetchEvents, isEventActive};
    

    现在使用它们

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

    【讨论】:

    • 在我的情况下不可行。我在该导出中有许多变量和方法,并且存在一些依赖性。问题在于异步调用。如果我删除异步,代码可以工作。
    • 没有异步方法也可以正常工作,你只需要异步调用它们
    • 但它打败了我的异步等待。我需要等待才能完成商店调度调用。
    • 好吧,你可能知道什么对你的代码更好
    猜你喜欢
    • 2023-02-17
    • 2021-06-24
    • 2020-02-13
    • 2021-08-28
    • 1970-01-01
    • 2022-06-12
    • 2020-11-11
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多