繁体   English   中英

Vue.js 在方法中导入 Axios 然后使用它

[英]Vue.js import Axios within method then use it

我有一个组件,如果某些数据已传入它,它可能不会请求 ajax 调用。 但是,如果数据尚未传入,我需要获取它,因此我想导入 Axios,然后无缘无故地导入它。

在尝试使用脚本之前,我如何等待脚本被导入,因为以下不起作用:

export default {
    props: {
        vehicleId: {
            type: Number|String,
            required: true,
            default: () => null
        },
        settings: {
            type: Object,
            default: () => null
        }
    },
    beforeCreate() {
        if (!this.settings) {
            const Axios = () => import('../../../axiosConfig');

            Axios.get('/api/v1/media-slider-settings').then(response => {
                this.settings = response.data;
            });
        }
    },

动态import返回一个 Promise,所以你必须使用then函数。

尝试这样的事情:

<script>
export default {
  beforeCreate() {
    if (!this.settings) {
      import('../../../axiosConfig').then(axios => {
        axios.get('/api/v1/media-slider-settings').then(response => {
          this.settings = response.data;
        });
      });
    }
  },
};
</script>

避免使用async/await的方法,因为生命周期函数在 Vue.js 中不支持异步。

你快到了, import()是异步的,所以只需执行以下操作:

// or use .then if you're not in an async function
const Axios = (await import('../../../axiosConfig')).default

Axios.get('/api/v1/media-slider-settings').then(response => {
  this.settings = response.data;
});

并注意import()返回模块,因此如果您需要默认导出(如您的情况),则需要获取.default属性,或者只需调用.someExportedName来导入命名导出(即来自模块的非默认导出) )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM