import { ElMessage } from 'element-plus'
function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
if (response.data.code === 0) {
return response
}
// 请求失败
console.log('response.code != 0', response.data)
ElMessage.error(response.data.message || '服务异常')
return Promise.reject(response.data)
}
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",
"axios": "^1.6.7",
"element-plus": "^2.5.5",
"pinia": "^2.1.7",
"vue": "^3.4.15",
"vue-router": "^4.2.5"
},
"devDependencies": {
"@rushstack/eslint-patch": "^1.3.3",
"@tsconfig/node20": "^20.1.2",
"@types/node": "^20.11.10",
"@vitejs/plugin-vue": "^5.0.3",
"@vue/eslint-config-prettier": "^8.0.0",
"@vue/eslint-config-typescript": "^12.0.0",
"@vue/tsconfig": "^0.5.1",
"eslint": "^8.49.0",
"eslint-plugin-vue": "^9.17.0",
"husky": "^8.0.0",
"lint-staged": "^15.2.2",
"npm-run-all2": "^6.1.1",
"pinia-plugin-persistedstate": "^3.2.1",
"prettier": "^3.0.3",
"sass": "^1.71.0",
"typescript": "~5.3.0",
"unplugin-auto-import": "^0.17.5",
"unplugin-vue-components": "^0.26.0",
"vite": "^5.0.11",
"vue-tsc": "^1.8.27"
},
组件库选择的是按需导入,如何解决?
在 Element Plus 官方文档中提到使用按需导入需要安装unplugin-vue-components
和unplugin-auto-import
这两款插件,文档中还提到:
WARNING
如果使用 unplugin-element-plus 并且只使用组件 API,你需要手动导入样式。
Example:
import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'
虽然不使用 unplugin-element-plus 但加入 import 'element-plus/es/components/message/style/css'
后问题确实解决了。期待后续的更新。
直接删去 import { ElMessage } from 'element-plus'
虽然 vscode 显示报错:找不到名称“ElMessage”,但是运行能正常显示。
可以在.eslintrc.cjs
文件内添加:
module.exports = {
globals: {
ElMessage: 'readonly',
ElMessageBox: 'readonly',
ElLoading: 'readonly'
}
}
向eslint声明全局变量,取消 .vue 文件内的报错。
关于方法二的补充:
还需要在 tsconfig.app.json
的 include 数组添加"auto-imports.d.ts","components.d.ts":
"include": ["env.d.ts", "src/**/*", "src/**/*.vue","auto-imports.d.ts","components.d.ts"],
重启 vscode 后生效。