Vue在调用异步接口上和jq有一些不同,官方推荐使用axios,下面来看看如何使用。
首先是在需要调用时import相关组件
import axios from 'axios'
然后在method中调用,可以用get和post两种方法,这点和jquery很像。
getData: function () {
axios.post('/activeinvestrank/getInvest')
.then(function (response) {
console.log('then ' + response.data)
})
}
最后调用他
<a v-on:click="getData" href="javascript:void(0);">测试</a>
然而会遇到个跨域的问题,如果使用了cli的npm run dev命令,独立运行页面,而如果有后台的ajax接口,接口地址和端口号肯定不一致,造成跨域,不过vue系统自带代理功能,能很好解决这个问题,在config\index.js目录下
Config\index.js
proxyTable: {
'/activeinvestrank/getInvest': {
target: 'http://192.168.4.18:8085',
changeOrigin: true,
pathRewrite: {
'^/activeinvestrank/getInvest': '/activeinvestrank/getInvest'
}
}
},
/activeinvestrank/getInvest
是接口名称,
target: 'http://192.168.4.18:8085',
是原来的地址和端口号
changeOrigin: true,
是否跨域
这样就能完美解决。
下面是jsonp的调用方式
先是import
import jsonp from 'jsonp'
类似于jq的方式
getJsonpData: function () {
jsonp('http://192.168.4.18:12306/sms/fetch?type=dev', {
param: 'callback',
timeout: 60000
}, function (err, data) {
if (err) {
console.error(err.message)
} else {
console.log(data)
}
})
},
调用方法
<input id="J_btn_code" type="button" v-on:click="getJsonpData" value="获取短信验证码"><br>
Vue中接口请求就到这里为止。
联系客服