Vue.js 是一个流行的前端框架,Axios 是一个流行的 JavaScript 库,用于发送 HTTP 请求。在 Vue.js 中使用 Axios,常见的写法如下:
1. 在单文件组件中导入 Axios:
<script>
import axios from 'axios'
export default {
data () {
return {
posts: []
}
},
mounted () {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data
})
.catch(error => {
console.log(error)
})
}
}
</script>
2. 在全局注册 Axios:
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$axios = axios
然后,可以在每个 Vue 组件中使用 this.$axios
调用 Axios:
<script>
export default {
data () {
return {
posts: []
}
},
mounted () {
this.$axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.posts = response.data
})
.catch(error => {
console.log(error)
})
}
}
</script>
无论哪种写法,Axios 都提供了丰富的 API,可以发送 GET、POST、PUT、DELETE 等请求,以及设置请求头、响应拦截器等功能。根据实际需求,选择合适的 API 和配置。
3.封装
axios({
url: '传入的api',
//对封装好的对象进行序列化,如果后台没说明可以直接传obj对象就行
data: {obj:JSON.stringify(obj)},
//定义get请求或者post请求
method: "post",
//设置参数的表头形式,这是表单形式传递
headers: {
"Content-Type": 'application/x-www-form-urlencoded'
},
//对data的参数转化为键值对
transformRequest: [function (data) {
let ret = '';
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
}
return ret
}]
}).then(res=>{
//后台成功请求200运行到这里
console.log(res)
}
})
.catch(err=>{
//后台请求失败运行到这里
});