【问题标题】:"TypeError: Cannot read property 'get' of undefined", Axios, Vue.JS“TypeError:无法读取未定义的属性'get'”,Axios,Vue.JS
【发布时间】:2020-12-18 10:54:54
【问题描述】:

尝试使用 axios 从 api 访问获取请求时,我从 Vue 收到这个奇怪的错误, 我收到“TypeError:无法读取未定义的属性 'get'”

 <template>
    <div class="home">
        <h1>{{ msg }}</h1>
        <p>Welcome to your new single-page application, built with <a href="https://vuejs.org" target="_blank">Vue.js</a>.</p>
    </div>
</template>

<script>
    var Vue = require('vue');

   // import axios from "axios";

    window.axios=require('axios');
    export default {
        name: 'Home',
        props: {
            msg: String
        },
        component: {
        },   
        mounted: function () {
            alert('Hi ');
            this.axios.get('https://api.github.com/users')
                .then(value => {
                    alert(value);
                         
                });
        }

    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>


 

【问题讨论】:

  • 应该只是axios.get,而不是this.axios.get。您可能会看到在某些示例中使用了this.axios,但在这些情况下,它们已将axios 存储在this 上,而您的代码中似乎并非如此。
  • 我还建议坚持使用import 方法,而不是使用requirewindow
  • 谢谢@skirtle,非常感谢先生:)

标签: vue.js vuejs2 axios vue-component vuex


【解决方案1】:

this 在您的情况下不引用window。更好的方法是在组件中导入axios

import axios from 'axios';

更有效的方法是在main.js 文件中全局设置一次:

Vue.prototype.$http = axios

并在任何你想要的地方使用它作为this.$http

【讨论】:

    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2020-07-14
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多