背景
基於 webpack 搭建的 vue 項目中,某個文件使用 async/await 報錯,例如:
<script>
export default {
name: "test",
methods: {
async queryUsers() {
// 配置請求參數
const options = { url: this.$constant.BACK_API.QUERY_USRS }
const users = await this.$request(options)
console.log(users)
}
},
mounted() {
this.queryUsers()
}
}
</script>
原因
在 vue 項目中使用async/await處理並行多個異步,因為項目中沒有使用 transform-runtime 將 es6+ 轉換成 es5。
解決方案
安裝 @babel/plugin-transform-runtime:
npm i @babel/plugin-transform-runtime -D
配置 .babelrc 文件:
{
"plugins": [
[
"@babel/plugin-transform-runtime"
]
]
}
若項目中不存在 .babelrc 文件,直接在項目根目錄下添加即可。
