“ TypeError:无法读取未定义的属性'get'”,Axios,Vue.JS

时间:2020-08-29 21:16:26

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

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

enter image description here

 <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>


 

1 个答案:

答案 0 :(得分:2)

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

import axios from 'axios';

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

Vue.prototype.$http = axios

并以this.$http的身份随处使用它