最近做的移动端Vue项目,需要本地与后台进行数据测试,所以用到axios跨域请求(顺便做移动端滑到底部加载更多),记录一下:
1、先安装axios:
npm install axios vue-axios --save
2、在main.js中配置:
import axios from 'axios'
import VueAxios from 'vue-axios'
import querystring from 'querystring' //传参时处理参数
Vue.use(VueAxios, axios)
Vue.prototype.querystring = querystring
3、在config下的index.js中进行 proxyTable 配置:
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
// 服务器地址为HTTPS
//target:'https://www.xxxx.com',
//secure: false,
// 服务器地址为HTTP
target:'http://www.xxxx.com', // 服务器地址
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/api': ''
}
}
},
// Various Dev Server settings
host: 'localhost ',
这里的“/api”就相当于target的地址,如果真是地址中后带“api”,可以直接除去“pathRewrite”这项,切记:这里配置完之后一定要重启项目,不然不会生效(我是踩了坑的)
4、组件中的post调用:
<template>
<div class="loadding-more" v-if="showlaoding"><load-more tip="正在加载..."></load-more></div>
<div class="loadding-more" v-else>数据已加载完!</div>
</template>
data () {
return {
list: [],
page: 1,
size: 10,
stopAddData: false, // 没有数据时不能加载
showlaoding: true, //显示加载
addPage: true, // 加载更多,阻止多次加载
}
},
mounted () {
this.$nextTick(function() {
var that = this;
this.getData();
document.querySelector('.content-scroll').addEventListener('scroll', function(){
if (this.scrollTop + this.clientHeight + 0 >= this.scrollHeight) {
if (that.stopAddData) {
return false;
} else {
if (!that.addPage) {
that.getData()
}
}
}
})
})
},
methods:{
// 获取服务器数据
getData() {
this.addPage = true;
var param = this.querystring.stringify({
p: this.page,
pagesize: this.size,
});
var offset = this.page*this.size;
this.$http({
method:'post',
url: '/api/xxxx', // 这里的api 是proxyTable配置中的/api
data: param,
}).then( function(res){
if (res.status === 200 ){
var data = res.data;
if (data.status === 1001 ){
var list = data.data.data;
if (list.length === 0) {
that.stopAddData = true;
that.showlaoding = false;
} else if (list.length > 0 && list.length <= that.size) {
list.map(function(n) {
that.list.push(n);
})
}
if (list.length === that.size) {
that.page += 1;
} else {
that.stopAddData = true;
that.showlaoding = false;
}
if (offset == data.data.count){
that.stopAddData = true;
that.showlaoding = false;
}
that.addPage = false;
}
}
}).catch( function(err) {
console.log(err)
})
}
}
5、组件的get调用:
this.axios.get('/api/xxx').then(function(res){
if (res.status === 200 ){
if (res.data.status === 1001 ){
that.user = res.data.data;
that.$store.commit('userInfo',res.data.data);
}
}
})
over!!!!