axios
axios可以在vue应用中访问一个 API 并展示其数据,是封装的ajax。
在使用axios前,需要先引入axios.js
使用axios获取信息
使用axios的get方法请求api并获取数据
<script type="text/javascript">
// 全局axios
Vue.prototype.$axios = axios
var vm = new Vue({
el:'#app',
data:{
list:[]
},
methods:{
getProduct(){
// 使用axios-get方法获取数据
this.$axios.get('https://www.yiqigoumall.com/index/items/is_best')
.then((res) => {
console.log(res.data.data)
this.list = res.data.data
})
.catch(err => {
console.log(err)
})
}
},
created(){
this.getProduct()
}
})
</script>
使用axios向api发送信息
使用axios向api发送信息的方法如下:
methods:{
// post
postAddress(){
this.$axios({
method:"post",
url:'https://www.yiqigoumall.com/address/createOrUpdate',
params:{
addressId:''
},
headers:{
"contentType":"application/json;charset=UTF-8"
},
data:{
userId:'67575555555553',
},
dataType:"json"
})
.then(res => {
console.log(res.data)
})
.catch(err => {
console.log(err)
})
}
}
}
}
fetch
fetch 是JS ES6中添加的一种新的方法,fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
下面是使用fetch请求api的方法
使用fetch无需引入新的js库,因为他是原生js方法。
methods:{
getProduct(){
fetch('https://www.yiqigoumall.com/index/items/is_best')
.then(result => result.json())
.then(res => {
console.log(res.data)
this.list = res.data
})
}
}