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

问题描述 投票:0回答:2

当我尝试使用 axios 从 api 访问 get 请求时,我从 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>


 
vue.js vuejs2 axios vue-component vuex
2个回答
6
投票
在您的情况下,

this
并不引用
window
。更好的方法是在组件中导入
axios

import axios from 'axios';

更高效的方法是在

main.js
文件中全局设置一次:

Vue.prototype.$http = axios

并在任何你想要的地方使用它

this.$http


0
投票

我遇到了同样的问题,只需添加 type="module" 即可解决我的问题。谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.