vue中使用axios

先给项目加个速,要是没有安装cnpm的先安装一下。

自己执行以下这句命令就好了:

npm install -g cnpm --registry=https://registry.npmmirror.com

接下来我们就可以进入axios的官网复制命令了:安装好之后引入到需要的组件中

<script>
//在单个组件中使用
    import axios from 'axios'
    export default {
     data() {
         return {
             news:[]
         }
     },   
     created() {
         let that = this;
         axios.get('/api/toutiao/index', {
            params: {
             type:"caijing",
             key:"c14887fe64c3c92f7cd9507b34e01257"
            }
        })
        .then(function (response) {
            console.log(response);
            that.news = response.data.result.data;
        })
        .catch(function (error) {
            console.log(error);
        });
     },
    }
</script>

如果我们在多个组件中都需要调用接口,那最好全局引入,不然每个引入就比较麻烦了。当然我们肯定要引入到入口文件main.js中。 

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

接下来我们继续在News.vue 组件中使用,注意和刚才的写法,微微不同了。这一次再也不用担心this的问题了。哈哈,真舒服。

  mounted() {
    this.axios
      .get("/api/toutiao/index", {
        params: {
          type: "caijing",
          key: "c14887fe64c3c92f7cd9507b34e01257",
        },
      })
      .then((response) => {
        console.log(response.data);
        this.news = response.data.result.data;
      });
  },


版权声明:本文为zhangli0421原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。