Vue利用vue-resource和axios发送ajax请求

1. vue-resource

vue的一个插件库, 非官方库, 在vue1.x中使用广泛. vue2.x中已很少使用, 之后都是用axios库.

使用步骤:

  • ①当前项目中安装: npm install vue-resource --save
  • ②在入口main.js文件中引入: import VueResource from ‘vue-resource’
  • ③调用Vue的use函数声明引用插件: Vue.use(VueResource)
  • ④通过 this.$http.get()或this.$http.post()发送请求.

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
<div v-if="repoURL">most star repo is <a target="_blank" :href="repoURL">{{repoName}}</a></div>
<div v-else>LOADING...</div>
</template>

<script>
export default {
data () {
return {
repoURL: '',
repoName: ''
}
},
mounted () {
const url = `https://api.github.com/search/repositories?q=vue&sort=stars`
this.$http.get(url).then(
response => {//请求成功时
const item = response.data.items[0]
this.repoURL = item.html_url
this.repoName = item.name
},
response => {//请求失败时
alert(response)
}
)
}
}
</script>

<style scoped>

</style>

2. axios

通用的 ajax 请求库, 第三方库. 官方推荐使用. vue2.x中广泛使用.

使用步骤:

  • ①当前项目中安装: npm install axios --save
  • ②在哪个组件中使用, 就要: import axios from ‘axios’
  • ③之后通过 axios.get()或axios.post() 发送请求.

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
<div v-if="repoURL">most star repo is <a target="_blank" :href="repoURL">{{repoName}}</a></div>
<div v-else>LOADING...</div>
</template>

<script>
import axios from 'axios'
export default {
data () {
return {
repoURL: '',
repoName: ''
}
},
mounted () {
const url = `https://api.github.com/search/repositories?q=vue&sort=stars`
axios.get(url).then(
response => {//请求成功时
const item = response.data.items[0]
this.repoURL = item.html_url
this.repoName = item.name
},
response => {//请求失败时
alert(response)
}
)//.catch(error => {//请求失败的回调函数也可以这样写
// alert(error)
// })
}
}
</script>

<style scoped>

</style>

评论