vue中get和post请求

现在

vue中和后台交互,首先要引用vue-resource.js

vue-resource.js是专门和后台进行交互

<!-- ==============引入vue-resource插=================--> 
<script src="../js/vueJs/vue-resource.js"></script>

vue的get请求

function getRequest(url, params) {
  return new Promise((resolve, reject) => {
    Vue.$http.get(
      url,
      {
        params: params
      },
      {emulateJSON: true}
    )
    .then((res) => {   //成功的回调
      resolve(res);
    })
    .catch((res) => {  //失败的回调
      reject(res);
    });
  });
}

vue的get请求传递参数的时候要用{params:{id:'1'}},这样来传递参数,否则就无法传递参数

vue的post请求

function postRequest(url, params) {
  return new Promise((resolve, reject) => {
    Vue.$http.post(
      url,
      {
        params
      },
      {emulateJSON: true}
    )
    .then((res) => {    //成功胡回调
      resolve(res.body);
    })
    .catch((res) => {   //失败的回掉
      reject(res.body);
    });
  });
}

例子--

methods: {
    research: function () {
        //post请求远程资源
        this.$http.post(
            //请求的url
            "http://www.hefeixyh.com/login.html",
            //请求参数,不能以get请求方式写:{params: {userName: "root123", passWord: "root123"}}
            {userName: "root123", passWord: "root123"},
            //解决跨域问题,不加无法跨域
            {emulateJSON: true}
        ).then(
            function (res) {
                console.log(res);
                this.msg = res.bodyText;
            },
            function (res) {
                console.log(res.status);
            }
        );
    }
}
原文地址:https://www.cnblogs.com/miangao/p/11976739.html