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

Rus*_*ion 5 vue.js vue-component axios vuex vuejs2

当尝试使用 axios 从 api 访问 get 请求时,我从 Vue 收到这个奇怪的错误,我收到“TypeError: Cannot read property 'get' of undefined”

在此输入图像描述

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


 
Run Code Online (Sandbox Code Playgroud)

Maj*_*awi 7

this在你的情况下没有提到window。更好的方法是axios在组件中导入:

import axios from 'axios';
Run Code Online (Sandbox Code Playgroud)

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

Vue.prototype.$http = axios
Run Code Online (Sandbox Code Playgroud)

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