vue3学习:axios输入城市名称查询该城市天气

说来惭愧,接触前端也有很长一段时间了,最近才学习axios与后端的交互。今天学习了一个查询城市天气的案例,只需输入城市名称,点击"查询"按钮便可以进行查询。运行效果如下:

案例只实现了基本的查询功能,没有用css进行美化,需要效果更好看一些,自己添加一些css样式就行。

说明如下:

一、头部引入

因为用到了vue3和axios,需要在头部引入vue3库文件和axios库文件,我这里是网页版,采用的是CDN方式。

html 复制代码
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、注册成为天气用户

因为要用到天气信息,所以需要注册成为气象数据接口服务平台用户。这里使用的是"天气API",该网站网址为http://www.tianqiapi.com/,网站界面如下。

1.注册:在页面底端,也就是页脚部分可以"马上注册",如图所示。

注册过程非常简单。注册成功以后,登录就可以使用了。

2.选择首页上的v62,如图所示。

我们代码中出现的baseURL,除了示例中的网址,baseURL: 'http://v1.yiketianqi.com',也可以使用请求示例中的网址。其中,id和appsecret就是注册后网站给提供的。

三、完整代码如下:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>输入城市名称,查询天气 </title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
	<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="container">
        <div>
            <input type="text" placeholder="请输入城市名" v-model="cityName" />
            <input type="button" value="查询" @click="handleWeather(cityName)" />
        </div>
        <div class="weather">
            <div v-if="weatherInfo.city != ''">
                <p><span>{{weatherInfo.date}}</span>&nbsp;&nbsp;<span>{{weatherInfo.week}}</span></p>
                <p><span>{{weatherInfo.city}}天气预报</span>&nbsp;&nbsp;<span>更新时间&nbsp;{{weatherInfo.update_time}}</span>
                </p><br />
                <p><span>天气:{{weatherInfo.wea}}</span></p>
                <p><span><span>空气质量:{{weatherInfo.air_level}},</span>{{weatherInfo.air_tips}}</span></p>
                <div v-if="weatherInfo.air_level=='优'">适宜出行</div>
                <div v-else>不适合出行</div>
                <p><span>现在温度:{{weatherInfo.tem}}度</span>&nbsp;&nbsp;<span>{{weatherInfo.tem2}}度~{{weatherInfo.tem1}}度</span>
                </p>
                <p><span>{{weatherInfo.win}}</span>&nbsp;&nbsp;<span>{{weatherInfo.win_speed}}</span></p>
                <p><span>降雨量:{{weatherInfo.rain_pcpn}}</span></p>
            </div>
        </div>
    </div>
    <script>
        const appObj = Vue.createApp({
            setup(props, context) {
                const cityName = Vue.ref('')
                const infoData = Vue.reactive({
                    weatherInfo: {
                        city: '',
                        date: '',
                        week: '',
                        update_time: '',
                        wea: '',
                        tem: '',
                        tem1: '',
                        tem2: '',
                        win: '',
                        win_speed: '',
                        air_level: '',
                        air_tips:'',
                        rain_pcpn:'',
                    }
                })

                //create创建axios实例
                const instance = axios.create({
                  baseURL: 'http://v1.yiketianqi.com'   
                })
                //添加请求拦截器
                instance.interceptors.request.use((config) => {
                    return config;
                }, (error) => {
                    console.log("请求出错")           //请求出错时的处理
                    return Promise.reject(error);
                })
                //添加响应拦截器
                instance.interceptors.response.use((response) => {
                    if (response.status === 200 && response.data) {//响应成功时的处理
                        console.log("响应成功")
                    }
                    return response
                }, (error) => {
                    console.log("响应失败")              //响应失败时的处理
                    return Promise.reject(error.response.data)
                })

                //async/await写法
                const handleWeather = async (name) => {
                    cityName.value = name
                    const res = await instance.get(
                        "/api",
                        {
                            params: {
                                unescape: 1,
                                version: 'v61',
                                appid: '123456789', //改成自己的
                                appsecret: '123456789',
                                city: name
                            }
                        }
                    )
               
                    infoData.weatherInfo.city = res.data.city
                    infoData.weatherInfo.date = res.data.date
                    infoData.weatherInfo.update_time = res.data.update_time
                    infoData.weatherInfo.week = res.data.week
                    infoData.weatherInfo.wea = res.data.wea
                    infoData.weatherInfo.tem = res.data.tem
                    infoData.weatherInfo.tem1 = res.data.tem1
                    infoData.weatherInfo.tem2 = res.data.tem2
                    infoData.weatherInfo.win = res.data.win
                    infoData.weatherInfo.win_speed = res.data.win_speed
                    infoData.weatherInfo.air_level = res.data.air_level
                    infoData.weatherInfo.air_tips = res.data.air_tips
                    infoData.weatherInfo.rain_pcpn = res.data.rain_pcpn
                }
                return {
                    cityName,
                    infoData,
                    ...Vue.toRefs(infoData),
                    handleWeather
                }
            }
        })
        appObj.mount('#container')  
    </script>
</body>
</html>
相关推荐
憧憬成为web高手5 小时前
ACTF 12307复现
前端·bootstrap·html
wordbaby6 小时前
Axios 上传大文件崩溃:鸿蒙 RNOH 下 XHR 返回空响应头引发的"假失败"
前端·react native
玛丽莲茼蒿6 小时前
Linux/Unix学习笔记(四)—— 进程管理
linux·学习·unix
wordbaby6 小时前
React Native 列表分页实战:下拉刷新与上拉加载的工程化方案
前端·react native
richxu202510016 小时前
学完了江科大STM32,下一步该怎么学?
stm32·单片机·嵌入式硬件·学习
wordbaby7 小时前
脱离 Tab 栏的艺术:React Native 全屏子页面的导航架构实践
前端·react native·harmonyos
网络与设备以及操作系统学习使用者7 小时前
Linux与Windows核心差异深度解析
linux·运维·网络·windows·学习
陈随易7 小时前
Redis 8.8发布,一定要更新
前端·后端·程序员
wordbaby7 小时前
React Native 新架构落地鸿蒙:跨三端政务级应用的工程实践与深度复盘
前端·react native·harmonyos
知识分享小能手8 小时前
Flask入门学习教程,从入门到精通,Flask智能租房——前期准备 知识点详解(5)
python·学习·flask