1.安装axios cnpm install --save axios 2.引入axios
在main.js入口文件里面进行引入
import axios from 'axios' 3.将axios注入vue的原型
只有将axios注入vue的原型中,在其他组件中就可以直接使用axios了,非常方便,我们可以把axios定义为vue原型中的属性,在其他组件中就可以通过this.$axios进行使用了。
Vue.prototype.$axios=axios 4.使用axios获取远程数据
在home.vue文件中添加create周期函数
created(){ this.$axios.get('http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20').then(res=>{ console.log(res); })
代码分析
this:指的是当前组件实例vue
axios是基于prmoise的基础上获取远程数据的工具,因此,我们可以通过get方法调用服务求的方法,使用回调函数的方法获取到数据,测试结果如下
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}data: {result: Array(20)}status: 200statusText: "OK"headers: {content-type: "text/html; charset=utf-8"}config: {url: "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}__proto__: Object