Vue + vux 實戰記錄(axios跨域)
阿新 • • 發佈:2019-02-19
最近做的移動端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!!!!