介绍 axios
Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。
get
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--随机笑话https://autumnfish.cn/api/joke -->
<title>Document</title>
</head>
<body>
<div id="app">
<button @click="getjoke">获取笑话</button>
<p>
{{joke}}
</p>
</div>
</body>
<script>
var app = new Vue({
el: "#app",
data: {
joke: ''
},
methods: {
getjoke: function () {
var that = this; //将this存到that中防止数据变化
// 方法1
//es6语法不需存储this
// axios.get("https://autumnfish.cn/api/joke").then(response => (
// that.joke = response.data
// )).catch(error => (console.log(error)));
// 方法2
axios.get("https://autumnfish.cn/api/joke").then(function(response){
that.joke=response.data;
},function(err){
console.log(err);
})
}
}
})
</script>
</html>
post
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="app">
{{ info }}
</div>
<script type = "text/javascript">
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
</script>
</body>
</html>
注意点
使用 response.data 读取 JSON 数据: