在 Vue 中使用 Axios

1 min read

最近在写前后端分离的项目,使用axios遇到了很多奇怪的错误,这篇文章用以记录axios常用的操作。

安装

npm install axios

引入

直接在main.js里全局引入即可。

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

使用

<template>
    <div v-for="item in info" :key="item">
        {{ item.title }}
    </div>
</template>

<script>
export default {
  name: "Demo",
  data() {
      return {
        info: {}
      };
  },
  mounted() {
      // POST 请求
      this.axios.post('/api/login', {
        username: 'admin',
        password: '123456'
      })
      .then(function (response) => { // 成功
            this.info = response.data
            console.log(response);
      })
      .catch(function (error) => { // 失败
            console.log(error);
      });
    
      // GET 请求
      this.axios.get('/api/info')
      .then(function (response) { // 成功
          this.info = response.data
          console.log(response);
      })
      .catch(function (error) { // 失败
          console.log(error);
      });
  };
}
</script>