Vue】五、Vue.js之Axios"/>
【Vue】五、Vue.js之Axios
后端程序员的vue学习之路
- 一、Axios
- 1、安装方法
- 2、GET 方法
- 普通请求
- async 请求
- 3、Post请求方法代码示例
- 2、delete.put等其他请求方法
一、Axios
我们只是在静态页面使用Vue.js,不涉及从后端接口获取数据动态渲染页面,而在实际项目开发中,通常需要前后端结合来实现页面的渲染,前端负责页面展示和交互,后端负责数据的存储和获取,这就会使用到ajax技术请求从后端接口获取数据;
Vue.js,包括React.js都推荐使用 axios 来完成 ajax 请求;
axios 是一个基于 Promise的HTTP库,可以用在浏览器和node.js中;
Github开源地址:
中文文档:
1、安装方法
1、直接下载js文件
<script src=".min.js"></script>
3、使用npm:
$ npm install axios
2、GET 方法
普通请求
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>test13</title><script src=".js"></script><script src=".min.js"></script>
</head><body><div id="app">{{ info }}</div><script type="text/javascript">new Vue({el: '#app',data() {return {info: null}},mounted() {axios.get('http://localhost:8080/info')//请求远程接口,那么这里会有跨域的问题.then(response => (this.info = response)).catch(function (error) {//请求失败处理console.log(error);});// axios// .get('http://localhost:8080/info')//请求远程接口,那么这里会有跨域的问题// .then(response => {// this.info = response// console.log(a);// })// .catch(error => {//请求失败处理// console.log(error);// });}})</script>
</body></html>
async 请求
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>test14</title><script src=".js"></script><script src=".min.js"></script>
</head><body><div id="app">{{ info }}</div><script type="text/javascript">new Vue({el: '#app',data() {return {info: null}},mounted() {// axios.get('http://localhost:8080/user?id=12345')// .then(response => {// this.info = response// console.log(response);// }).catch(error => {// console.log(error);// })// axios.get('http://localhost:8080/user', {// params: {// id: 12345,// name: "cat"// }// }).then(response => {// this.info = response// console.log(response);// console.log(a)// }).catch(error => {// this.info = error// console.log(error);// })//async/await是ECMAScript 2017的一部分,在Internet Explorer和旧浏览器中不受支持,因此请谨慎使用;async function getUser() {try {console.log("000");const response = await axios.get('http://localhost:8080/user?id=12345');console.log(response);this.info = responseconsole.log("111");} catch (error) {console.error(error);}console.log("333");}//调用getUser()}})</script>
</body></html>
3、Post请求方法代码示例
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>test15</title><script src=".js"></script><script src=".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('http://localhost:8080/user')// .then((response) => {// this.info = response// console.log(response);// }).catch((error) => {// console.log(error);// });axios.post('http://localhost:8080/user2', {id: 123,name: 'cat'}).then((response) => {this.info = responseconsole.log(response);}).catch((error) => {console.log(error);});}})</script>
</body></html>
2、delete.put等其他请求方法
axios.delete(url[, config])
axios.put(url[, data[, config]])
更多推荐
【Vue】五、Vue.js之Axios
发布评论