一. 什么是Axios
1. axios 是独立于 vue 的一个项目,不是 Vue 的一部门 2. axios 通常和 Vue 一起利用,实现 Ajax 利用 3. Axios 是一个基于 promise 的 HTTP 库 axios官方文档
二.引入Axios库文件
1.可以直接引用
2.可以下载Axios的js文件导入
下载此js文件
三.利用Axios共同Vue发出Ajax哀求案例
在Vue中利用Axios,向服务器发送Ajax哀求,将获取的json数据表现界面

- <!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">
- <title>title</title>
- </head>
- <body>
- <div id="app">
- <h1>妖怪列表</h1>
- <table border="1" width="300">
- <tr>
- <td>名字</td>
- <td>年龄</td>
- </tr>
- <tr v-for="monster in monsterList">
- <td>{{monster.name}}</td>
- <td>{{monster.age}}</td>
- </td>
- </tr>
- </table>
- </div>
- <script src="vue.js"></script>
- <script src="axios.min.js"></script>
- <script>
- var app = new Vue({
- el: '#app',
- // data / created() / methods 是一个固定结构
- data: {
- monsterList: []//数组
- },created() { //在页面渲染前执行,调用 list()
- this.list()
- },methods: {
- list() {
- axios.get('http://localhost:63342/axios/data/response.json')
- .then(response => {
- console.log("response=",response);
- console.log("response.data=",response.data);
- console.log("response.data.data=",response.data.data);
- console.log("response字符串=",JSON.stringify(response.data));
- this.monsterList = response.data.data.items;
- })
- .catch(error => {
- console.log(error)
- })
- }
- }
- })
- </script>
- </body>
- </html>
复制代码
留意点
* 1. 利用 axios 发送 ajax 哀求
* 2. 语 法 格 式 axios. 请 求 方 式 ( 请 求 路 径 ).then( 箭 头 函
数).catch(箭头函数)
* 3. 哀求乐成,实行 then 的函数, response 就是返回的数据, 名
字由步伐员确定
* 4. 哀求失败, 实行 catch 的函数
* 5. this.monsterList = response.data.data.items 把 返 回 的
data.items 赋给 monsterList
* 6. 这里的 http://127.0.0.1:63342/axios/response.json 路
径须要根据实际的端口和资源名来修改
效果:
留意点:
在此网站可以将json对象转换为字符串https://www.json.cn/
|