vue 前后台通信

使用vue-resource请求数据

1.安装vue-resource

npm install vue-resource --save或cnpm install vue-resource --save

2.main.js里面引入vue和vue-resource

import VueResource from "vue-resource"

Vue.use(VueResource );

3.在对应的组件里面使用vue-resource

在methods里面写个方法,在mounted里面调用次方法

data(){

list:[]//用来存储接口请求回来的数据

},

methods:{

requestData(){

//这里面也也用jsonp请求this.$http.jsonp,后台api接口支持jsonp,url就是后台的接口,项目里面后单独统一管理,这里面要注意有请求的时候this的指向问题,不使用this的箭头函数的时候我们要留住this.

this.$http.get("url").then((response)=>{

console.log(response);

this.list=response.body.data//具体看接口返回来的数据

},function(error){

console.log(error)

})

}

}

4.在mounted里面调用这个方法

mounted:{

this.requestData()

}

5.组件内可以对list进行循环获取想要的数据。

使用axios请求数据(与vue-resource类似)

1.首先安装axios

npm install  axios --save或cnpm install axios --save

2.引入axios,在mounted里面写逻辑。如下例子:

import axios from "axios";//引入axios
mounted(){

var _this = this;
/*我淘的币*/
axios.get(httpUrl.myOrder, {//这里后台接口进行了管理在httpUrl对象中,就是后台提供的接口
  headers: {
    "Authorization": "Bearer " + this.token
  }
}).then(function(res) {
  _this.myOrderList = res.data.data.data; /*我的淘币列表*/ //在data中可以定义变量来存储这些获得的数据。
  _this.myOrderPage = res.data.data.per_page; /*显示条数*/
  _this.myOrderTotal = res.data.data.total; /*总条数*/
}, function(err) {
  console.log(err)
})
这个一个简单的例子说明前后台通信,其他需要根据业务逻辑去实现。

猜你喜欢

转载自blog.csdn.net/weixin_42554311/article/details/81774111