命令行:cnpm install axios --save
main.js 引入:
import axios from 'axios';
Vue.prototype.axios = axios.create({
headers: {'content-type': 'application/json'}
})
Vue.prototype.$post = function (url, data = {}) {
return new Promise((resolve, reject) => {
this.axios.post(url, data).then(res => {
resolve(res)
}).catch(function (error) {
reject(error)
})
})
}
使用方法:
let that = this;
that.$post('地址', {
参数
}).then(res => {
}).catch(function(error) {
console.log(error)
})
如果发生跨域问题在config下的index。js加
'/api': {
target: '地址',
changeOrigin: true,
pathRewrite: {
'^/api': '/' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
}
},
'/api1': {
target: '地址',
changeOrigin: true,
pathRewrite: {
'^/api1': '/' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
}
}
使用方法
let that = this;
that.$post('/api/roll/getRoll', {
type: '1'
}).then(res => {
}).catch(function(error) {
console.log(error)
})