软件教程 2025年08月6日
0 收藏 0 点赞 686 浏览 4323 个字
摘要 :

一、前置知识 其中部分知识不必深究,了解会用即可。 ES6: Promise ES7: async和await http协议 ajax 二、初识axios 1、axios官网:http://www.axios-js.com/ 2、ax……

一、前置知识

其中部分知识不必深究,了解会用即可。

  • ES6: Promise
  • ES7: async和await
  • http协议
  • ajax

二、初识axios

1、axios官网:http://www.axios-js.com/
2、axios官网中文文档:http://www.axios-js.com/zh-cn/docs/

3、什么是 axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

4、特性

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

三、使用axios异步获取数据
1、axios语法说明

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);
  });

2)执行Post请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

更多语法可以去参考官网文档。

2、案例实现

1)由于我们目前还没有搭建自己的服务器端,所以在此通过调用阿里云的免费api获取天气预报数据显示

2)注册阿里云账号,然后访问https://market.aliyun.com/products/57126001/cmapi014123.html#sku=yuncode812300000购买免费体验套餐。
Vue系列入门教程(8)——axios异步请求获取天气预报
3)购买后在控制台已购买服务中心可以查看对应的AppKey、 AppSecret、AppCode(重要,需要保密)
Vue系列入门教程(8)——axios异步请求获取天气预报
3、使用HBuildX新建vue-cli项目,名为weather,过程在此不再赘述,如果不会,请参考Vue系列入门教程(7)——实现简单轮播图

4、为weather安装axios,这里我们使用npm安装方式,打开项目终端,使用如下指令(安装好的axios在node_modules中):

npm install axios

Vue系列入门教程(8)——axios异步请求获取天气预报
5、新建Weather.vue组件(其中具体的参数含义,api使用方法参考api文档,注意替换你的APPCODE

<template>
    <div>
        <h1>{{title}}</h1>
        <!-- 简便起见,我们就只显示3个数据 -->
        日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}}
    </div>
</template>

<script>
    // 导入axios
    import axios from 'axios'
    //导出
    export default {
        name:"Weather",
        data(){
            return {
                title:"淮安明天的天气预报",
                // 明天天气状况封装成对象,注意要与响应中的f2属性名称保持一致
                f2:{
                    day:"",
                    day_weather:"",
                    day_air_temperature:''
                }
            }
        },
        methods:{
            getWeather(){
                // 发送get请求,请求地址和参数参考阿里云文档
                axios.get("http://saweather.market.alicloudapi.com/area-to-weather",{
                    // 文档要求请求头带Authorization认证
                    headers:{Authorization:'APPCODE 你的APPCODE'},
                    // 地区参数-支持的地区参考文档
                    params: {
                        area:'淮安'
                    }
                }).then(response=>{
                    // 使用箭头函数否则this访问不到data
                    // 打印响应查看返回的json数据结构
                    console.log(response);
                    // 获取明天的数据并赋值
                    this.f2 = response.data.showapi_res_body.f2;
                })
            }
        },
        // 生命周期方法-模板或el对应的html渲染完成后再调用里面的方法
        mounted(){
            this.getWeather();
        }
        
    }
</script>

<style scoped>

</style>

6、在App.vue中导入、注册、使用

<template>
  <div id="app">
      <Weather></Weather>
  </div>
</template>

<script>
import Weather from './components/Weather.vue'

export default {
  name: 'app',
  components: {
      Weather
  }
}
</script>

<style>
</style>

7、运行至浏览器
Vue系列入门教程(8)——axios异步请求获取天气预报

3、优化代码

以上的代码可以优化,我们现在优化下代码结构。
1,、在src目录下新建services目录,提取出一些方法与配置,方便复用

2、AppCode和请求地址都是常量,多出可能会用到,我们可以将其放到一个配置文件中,我们在services目录下新建config.js文件,内容如下:

// 导出AppCode
export var AppCode='你的APPCODE'
export var SevenDayUrl='http://saweather.market.alicloudapi.com/area-to-weather'

3、在services目录新建weatherService.js,内容如下:

// 导入axios和AppCode
import axios from 'axios'
import {AppCode} from './config.js'
import {SevenDayUrl} from './config.js'
// 导出根据地区获取明天天气的方法
export async function getWeather(area){
    //发送请求 使用await等待响应同时方法上要加上async表示异步
    var response = await axios.get(SevenDayUrl,{
        // 文档要求请求头带Authorization认证 使用ES6模板字符串拼接
        headers:{Authorization:`APPCODE ${AppCode}`},
        // 地区参数-支持的地区参考文档
        params: {
            area
        }
    });
    // 返回明天天气数据
    return response.data.showapi_res_body.f2;
}

4、修改Weather.vue如下:
一般而言,调用weatherService.js中的方法有两种方式,这里我们用两种方式实现Weather.vue,任选一种即可:
1)第一种:使用then

<template>
    <div>
        <h1>{{title}}</h1>
        <!-- 简便起见,我们就只显示3个数据 -->
        日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}}
    </div>
</template>

<script>
    // 导入weatherService.js
    import {getWeather} from '../services/weatherService.js'
    //导出
    export default {
        name:"Weather",
        data(){
            return {
                title:"淮安明天的天气预报",
                f2:{
                    day:"",
                    day_weather:"",
                    day_air_temperature:''
                }
            }
        },
        // 生命周期方法-模板或el对应的html渲染完成后再调用里面的方法
        mounted(){
            getWeather('淮安').then(response=>{
                // 使用箭头函数否则this访问不到data
                // 打印响应查看返回的json数据结构
                console.log(response);
                // 获取明天的数据
                this.f2 = response;
            });
        }
    }
</script>

<style scoped>

</style>

2)第二种:使用async和await

<template>
    <div>
        <h1>{{title}}</h1>
        <!-- 简便起见,我们就只显示3个数据 -->
        日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}}
    </div>
</template>

<script>
    // 导入weather.js
    import {getWeather} from '../services/weatherService.js'
    //导出
    export default {
        name:"Weather",
        data(){
            return {
                title:"淮安明天的天气预报",
                f2:{
                    day:"",
                    day_weather:"",
                    day_air_temperature:''
                }
            }
        },
        async mounted(){
            //模板或el对应的html渲染完成后再调用里面的方法
            var response = await getWeather('淮安');
            // 使用箭头函数否则this访问不到data
            // 打印响应查看返回的json数据结构
            console.log(response);
            // 获取明天的数据
            this.f2 = response;
        }
        
    }
</script>

<style scoped>

</style>

5、运行至浏览器,测试效果与上面一样

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.zuozi.net/5882.html

管理员

相关推荐
2025-08-06

文章目录 一、Promise基础回顾 二、Promise 与 axios 结合使用场景及方法 (一)直接返回 axios …

269
2025-08-06

文章目录 一、模块初始化时的内部机制 二、常见导出写法的差异分析 (一)写法一:module.exports…

107
2025-08-06

文章目录 一、ResizeObserver详解 (一)ResizeObserver是什么 (二)ResizeObserver的基本用法 …

683
2025-08-06

文章目录 一、前期准备工作 (一)下载相关文件 (二)安装必要工具 二、处理扣子空间生成的文件…

338
2025-08-06

文章目录 一、官方文档 二、自动解包的数据类型 ref对象:无需.value即可访问 reactive对象:保持…

371
2025-08-06

文章目录 一、Hooks的工作原理 二、在if语句中使用Hook会出什么岔子? 三、React官方的Hook使用规…

843
发表评论
暂无评论

还没有评论呢,快来抢沙发~

助力内容变现

将您的收入提升到一个新的水平

点击联系客服

在线时间:08:00-23:00

客服QQ

122325244

客服电话

400-888-8888

客服邮箱

122325244@qq.com

扫描二维码

关注微信客服号