Vue3导入legends.js报错:请求的模块未提供名为legend的导出如何修复
问题原因
你的报错由两个核心问题导致:
legends.js中没有声明过名为legend的变量/对象,直接执行export default legend本质是导出了一个未定义的值- 导入时使用了
{ legend }的命名导入语法,但你代码中使用的是export default的默认导出语法,二者不匹配
修复方案
方案1:使用默认导出(推荐)
- 修改
legends.js代码,先封装legend对象再导出,同时修复this指向问题(模块内的函数无法直接访问Vue组件的this,需要把参数显式传入):
import axios from "axios"; const API_URL = "http://localhost:8000/api"; // 声明legend对象,封装工具方法 const legend = { add(url, newRole) { axios .post(`${API_URL}/${url}`, newRole) .then((res) => {}) .catch((error) => { console.log("ERRRR:: ", error.response.data); }); }, remove(url, roleInfo) { axios .post(`${API_URL}/${url}`, roleInfo) .then((res) => {}) .catch((error) => { console.log("ERRRR:: ", error.response.data); }); } } export default legend
- 修改
manageRoles.vue的导入语句,默认导出不需要加花括号,同时调用方法时传入对应参数:
// 去掉导入时的花括号 import legend from "/src/legends.js"; // methods内调用时传参 methods: { addRole() { legend.add(`roles/createRole`, this.newRole); this.$router.push("/manager/roles"); }, removeRole() { legend.remove(`roles/deleteRole`, this.roleInfo); // 注意删除接口地址不要写错成createRole this.$router.push("/manager/roles"); }, }
方案2:使用命名导出
如果要保留{ legend }的导入写法,直接修改legends.js的导出语法为命名导出即可:
// legends.js内把export default改成命名导出 export const legend = { // 和方案1的对象内容完全一致 }
额外注意
你原代码中删除角色调用的接口是roles/createRole,明显是复制粘贴错误,需要替换为实际的删除接口地址,否则功能无法正常运行。
内容的提问来源于stack exchange,提问作者Joker Dark Knight
相关产品推荐
相关产品推荐

