vue.js使用axios

使用axios的两种调用方式

1.安装axios

$ cnpm install axios

 

2.在vue入口文件main.js中引入(推荐全局引入),或是在当前页面中引入(局部)

import axios from 'axios';

 

方法一:

在页面中直接调用,代码如下:

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
      .catch(error => console.log(error))
} })

 

方法二:

如果我们的页面经常需要请求接口获取数据,而且逻辑代码比较多的话,不妨将axios提取出来,封装到一个api的文件中,然后在页面中引入直接调用,这样看起来页面会简洁很多

接口全部放到api文件中方便管理,API文件代码如下:

api/index.js

import _axios from 'axios'

/**
 * 配置axios的新实例
 */
const axios = _axios.create({
    baseURL: '',
    timeout: 1000
})

/**
 * 错误、警告提示
 */
axios.interceptors.response.use(function (response) {
  const { data } = response
  if (data.code !== 0) {
    Vue.prototype.$snack.error({
      message: data.message
    })
    return Promise.reject(data)
  } else {
    return data.data
  }
}, function (error) {
  Vue.prototype.$snack.error({
    message: error.message
  })
  return Promise.reject(error)
})

export const userApi = {
  //获取用户列表
  getUserList (params) {
    return axios({
      url:  '/api/user/users',
      method: 'get',
      params
    })
  },
//删除用户 deleteUser (id) { return axios({ url: '/api/user/user', method: 'delete', params: { id } }) } }

 

页面引入

user/index.vue

import {userApi} from '../../api'

export default {
  data:(){
      return {
          userList:[],
          offset: 0,
          pageSize: 10
        }  
    },
     methods: {
        //获取用户列表
        async getUserList(){
            const params = {
                offset: this.offset,
                pageSize: this.pageSize
            }
          this.userList = await userApi.getUserList(params)
      }
    },
  。
  。
  。
  。 }

 

还不清楚的可以看下官方文档 https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

posted @ 2018-12-04 10:44  土豆儿哥  阅读(3355)  评论(0编辑  收藏  举报