【问题标题】:Vuejs - Can I use an imported function in my global router.beforeEachVuejs - 我可以在我的全局 router.beforeEach 中使用导入的函数吗
【发布时间】:2020-04-18 07:53:36
【问题描述】:

我正在尝试在我的全局路由器防护中使用导入的函数。但我收到了这个错误: getCurrentStage is not defined

getCurrentStage 是从shops.js 导入的

shop.js 看起来像这样

import axios from 'axios'

export function getCurrentStage() {
    axios.get("/admin/wine_app/shops").then(response => {
      return response.data.current_stage;
    });
}

export default getCurrentStage

然后我像这样导入它:import getCurrentStage from '../api/shops'

然后尝试在我的全局路由器保护中像这样使用它:

router.beforeEach((to, from, next) => {
  if(to.name == null){
    let current_stage = getCurrentStage();
  }
  else {
    next();
  }
})

但是我得到了未定义的错误。有什么帮助吗?

【问题讨论】:

  • shop.js 还是shops.js?你两个都用过
  • @Dan 谢谢.. 它的shops.js 我已经在问题中解决了它
  • 你是导出函数两次吗?
  • 错误信息x is not defined 通常表示标识符x 在当前范围内根本没有被声明。它与拥有undefined 的值不同,它比这更极端。问题中提供的代码应该可以正常工作。我自己运行它没有问题。您能否确认您执行import 的行与您的路由器保护在同一个文件中?如果是这样,那么我最好的猜测将是缓存问题。向这两个文件添加一些控制台日志记录,以确认您没有获得这些文件的旧副本。

标签: vue.js vue-router


【解决方案1】:

您没有在导出的函数中返回任何内容。您需要返回 axios 承诺,以便 current_stage 有一些返回给它:

export function getCurrentStage() {
  return axios.get("/admin/wine_app/shops").then(response => {
    return response.data.current_stage;
  });
}

这只会返回承诺,因此您需要使用该承诺执行一些适当的异步操作,例如 await.then。例如:

getCurrentStage().then(stage => {
  current_stage = stage;
});

您还导出了两次函数,这可能不是故意的。如果您只打算通过导入默认值来检索它,则不需要第一个 export

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多