vuejs 使用axios 使用方法

引入注册全局

// main.js 引入

import axios from 'axios'
//  插件。
Vue.prototype.$http = axios

 全局使用,url必须全写,否者404.

create 构建一个 axios实例来使用,也可以直接$http.get 使用 $http 是在main.js中注册的axios

参考 

https://github.com/axios/axios

GET 代码

  var instance = this.$http.create({
        headers: {'content-type': 'application/x-www-form-urlencoded'}
      })
      instance.get('http://127.0.0.1:8082/index/Ajaxget')
        .then(function (response) {
          console.log(response)
        })
        .catch(function (error) {
          console.log(error)
        })
    },

POST 代码

export default {
  name: 'App',
  // 定义数据对象
  data () {
    return {
      user: '',
      password: '',
      ifLogin: true
    }
  },
  // 定义事件对象 methods
  methods: {
    // 登录
    onLogin: function () {
      var there = this
      var instance = this.$http.create({
        headers: {'content-type': 'application/x-www-form-urlencoded'}
      })
      instance.post('https://easy-mock.com/mock/5aa916df93041f109b6e8fba/example/login/login', {
        firstName: there.user,
        lastName: there.password
      })
        .then(function (response) {
          console.log(response.data.data.iflogin)
          console.log(there.ifLogin)
          there.ifLogin = !response.data.data.iflogin
        })
        .catch(function (error) {
          console.log(error)
        })
    }

  }

猜你喜欢

转载自my.oschina.net/u/3529405/blog/1628830