Vue& axios的基本使用

Vue.js Ajax(axios)

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

Github开源地址: https://github.com/axios/axios

安装方法

  1. 使用 cdn:
    1
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  2. 使用 npm:
    1
    npm install axios
  3. 其他

基本使用

  1. axios必须先导入才可以使用
  2. 使用get或post方法即可发送对应的请求
  3. then方法中的回调函数会在请求成功或失败时触发
  4. 通过回调函数的形参可以获取响应内容,或错误信息

示例:

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
36
37
38
39
40
41
42
<body>
<input type="button" value="get请求" class="get" />
<input type="button" value="post请求" class="post" />
<!-- 官网提供的axios在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
/*
接口1:随机笑话
请求地址:https://autumnfish.cn/api/joke/list
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
*/
document.querySelector(".get").onclick = function () {
axios
.get("https://autumnfish.cn/api/joke/list?num=6")
.then(function (response) {
console.log(response);
}),
function (err) {
console.log(err);
};
};
/*
接口2:用户注册
请求地址:https://autumnfish.cn/api/user/reg
请求方法:post
请求参数:username(用户名,字符串)
响应内容:注册成功失败
*/
document.querySelector(".post").onclick = function () {
axios
.post("https://autumnfish.cn/api/user/reg", { username: "jack" })
.then(function (response) {
console.log(response);
}),
function (err) {
console.log(err);
};
};
</script>
</body>

querySelector() 方法返回文档中匹配指定 CSS 选择器的一个元素。

注意: querySelector() 方法仅仅返回匹配指定选择器的第一个元素。如果你需要返回所有的元素,请使用 querySelectorAll() 方法替代。

axios+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
36
37
38
39
40
<body>
<div id="app">
<input type="button" value="获取笑话" v-on:click="getJoke" />
<p>{{joke}}</p>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 官网提供的axios在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
/*
接口1:随机笑话
请求地址:https://autumnfish.cn/api/joke/list
请求方法:get
请求参数:num(笑话条数,数字)
响应内容:随机笑话
*/
var app = new Vue({
el: "#app",
data: {
joke: "很好笑的笑话",
},
methods: {
getJoke: function () {
console.log(this.joke);
var that = this;
axios
.get("https://autumnfish.cn/api/joke")
.then(function (response) {
// console.log(response);
console.log(response.data);
// console.log(this.joke);
that.joke = response.data;
}),
function (err) {};
},
},
});
</script>
</body>

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!