1.1 axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
axios的github:https://github.com/axios/axios
1.2 引入axios
可以用script引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
引入axios-0.18.0.js
1.3 案例
1.3.1 get请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
1.3.2 post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
为方便起见,为所有支持的请求方法提供了别名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
1.4 代码:
【需求】:创建data/user.json文件
使用axios读取user.json文件的内容,并在页面上输出内容。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>vuejs中axios数据调用</title>
<script src="vue-2.5.17.js"></script>
<script src="axios-0.18.0.js"></script>
</head>
<body>
<div id="app">
{{message}}
</div>
</body>
<script>
var vm = new Vue({
el: "#app",
data: {
message: ''
},
methods: {
init: function(){
axios.get("./data/user.json").then(function(response){
// alert(response);
alert(JSON.stringify(response))
alert(response.data[0].username);
})
}
},
created: function(){
this.init();
}
});
</script>
</html>
创建data目录,创建user.json
[
{"username":"张三","age":22},
{"username":"李四","age":21},
{"username":"王五","age":20},
{"username":"赵六","age":23}
]