Vue问题集

axios安装/使用及如何解决‘axios is not defined’

版权声明:本问题解决方案为CSDN博主「Icon_酱」的原创文章,遵循CC 4.0 BY-SA版权协议,转载附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yytIcon/article/details/90713049

安装axios

1、使用npm

$ npm install axios

2、使用 bower:

$ bower install axios

3、使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用axios

1、使用例子

    sendGet() {
            axios.get('http://localhost:3000/info', {
                params:{
                     name:'aa',
                     age:22
                 }
              })
              .then(res => {
                console.log(res);
              }).catch(err => {
                console.log(err);
              })
          }
但是在运行的时候会报错,显示axios  is not defined

2、解决办法

在main.js里写
    import axios from 'axios';
    Vue.prototype.$axios = axios;
然后将上述代码改成
    sendGet() {
            this.$axios.get('http://localhost:3000/info', {//这里将axios.get 改为this.$axios.get
                params:{
                    name:'aa',
                    age:22
                }
              })
              .then(res => {
                console.log(res);
              }).catch(err => {
                console.log(err);
              })
          }
这样就避免了“axios  is not defined”的错误

posted @ 2021-03-29 09:12  非职业天使  阅读(56)  评论(0编辑  收藏  举报