前端Axios搭配Vue(认清Axios,Axios团结Vue发出Ajax哀求,返回JSON数据案例!简便易懂。)

[复制链接]
发表于 2026-4-24 08:48:36 | 显示全部楼层 |阅读模式
一. 什么是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数据表现界面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>title</title>
  8. </head>
  9. <body>
  10. <div id="app">
  11.     <h1>妖怪列表</h1>
  12.     <table border="1" width="300">
  13.         <tr>
  14.             <td>名字</td>
  15.             <td>年龄</td>
  16.         </tr>
  17.         <tr v-for="monster in monsterList">
  18.             <td>{{monster.name}}</td>
  19.             <td>{{monster.age}}</td>
  20.             </td>
  21.         </tr>
  22.     </table>
  23. </div>
  24. <script src="vue.js"></script>
  25. <script src="axios.min.js"></script>
  26. <script>
  27.     var app = new Vue({
  28.         el: '#app',
  29. // data / created() / methods 是一个固定结构
  30.         data: {
  31.             monsterList: []//数组
  32.         },created() { //在页面渲染前执行,调用 list()
  33.             this.list()
  34.         },methods: {
  35.             list() {
  36.                 axios.get('http://localhost:63342/axios/data/response.json')
  37.                     .then(response => {
  38.                         console.log("response=",response);
  39.                         console.log("response.data=",response.data);
  40.                         console.log("response.data.data=",response.data.data);
  41.                         console.log("response字符串=",JSON.stringify(response.data));
  42.                         this.monsterList = response.data.data.items;
  43.                     })
  44.                     .catch(error => {
  45.                         console.log(error)
  46.                     })
  47.             }
  48.         }
  49.     })
  50. </script>
  51. </body>
  52. </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/

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表