5.使用axios

1.依賴
在項目目錄,用命令行
npm install axios --save
2.導入項目中
在main.js中:
import axios from 'axios'
Vue.prototype.$axios = axios
3.不使用Vue的跨域解決方法,容易出問題。
直接使用axios的方式知道你BaseUrl即可。
3.0修改config/dev.env.js(開發環境),config/prod.env.js(發布環境)
增加BASE_API:
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_API: '"http://localhost:9011"'
})
3.1創建 src/utils/request.js:

import axios from 'axios';
const service = axios.create({
  timeout: 1500,
  baseURL: process.env.BASE_API
})
export default service

3.2以brand表為例,創建src/api/brand.js

import query from '@/utils/query'
const group_name = 'brand'
export default {
  save(pojo) {
    return query({
      url: `/${group_name}`,
      method: 'post',
      data: pojo
    })
  },
  deleteById(id) {
    return query({
      url: `/${group_name}/${id}`,
      method: 'delete'
    })
  },
  update(id, pojo) {
    return query({
      url: `/${group_name}/${id}`,
      method: 'put',
      data: pojo
    })
  },
  findAll() {
    return query({
      url: `/${group_name}`,
      method: 'get'
    })
  },
  findById(id) {
    return query({
      url: `/${group_name}/${id}`,
      method: 'get'
    })
  }
}

3.3在組件中使用
<script>中:

import brandApi from '@/api/brand'
......
methods: {
      save() {
        brandApi.save({
          name: "SM",
          first_char: "S"
        })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      deleteById() {
        brandApi.deleteById("30")
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      update() {
        brandApi.update("26", {
          name: "三星",
          first_char: "S"
        })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      findAll() {
        brandApi.findAll()
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      findById() {
        brandApi.findById("2")
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容