vue axios实战,请求天气预报接口

效果预览
在这里插入图片描述
创建流程

1. 创建项目目录

mkdir test2

2. 进入目录

cd test2

3. 引入vue

引入vue, 一路敲回车就行了

npm init vue@latest

4. 启动项目

创建成功,启动项目

cd vue-project
npm install
npm run dev

执行run 后的访问结果

> vue-project@0.0.0 dev
> vite


  VITE v4.0.1  ready in 401 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help

访问 http://localhost:5173/ 可以看到这个界面,就说明vue启动成功
在这里插入图片描述

5. 引入axios

先按control + c 退出运行界面, 然后引入axios

npm i axios

6. 粘贴axios请求天气代码

打开这个页面 /vue-project/src/components/HelloWorld.vue 把下面代码全部覆盖进去, 之前的删掉就行

<script>
	import axios from 'axios';
	export default {
		data() {
			return {
				img: '',
				weather: ''
			}
		},
		mounted() {
			let appid = '';//43656176
			let appsecret = '';//I42og6Lm
			console.log('mounted')
			axios({
				method: 'get',
				url: 'http://v0.yiketianqi.com/api/worldchina?appid=' + appid + '&appsecret=' + appsecret
			}).then(res => {
				console.log(res.data);
				this.weather = res.data
				this.img = 'https://xintai.xianguomall.com/skin/peach/' + res.data.day.phrase_img + '.png';
			});
		},
	}
</script>

<template>
	<div v-if="weather" style="text-align: center;">
		<img alt="Vue logo" class="logo" src="/src/assets/logo.svg" width="125" height="125" />
		<h3>{{weather.city}} 今日天气</h3>
		<h3>{{weather.month[0].night.temperature}}℃ ~ {{weather.month[0].day.temperature}}<img v-bind:src="img" width="20" style="vertical-align: sub;" /> {{weather.day.phrase}}
		</h3>
		<p>空气质量:<a>{{weather.day.air_level}}</a> &nbsp;&nbsp;气压:<a>{{weather.day.altimeter}}mb</a> &nbsp;&nbsp;湿度:<a>{{weather.day.humidity}}%</a></p>
		<p>白天:{{weather.month[0].day.narrative}}</p>
		<p>夜间:{{weather.month[0].night.narrative}}</p>
		<p style="padding: 30px 0; color:#999999;">数据来源:<a href="http://tianqiapi.com/index/doc?version=worldchina" target="_blank">Tianqiapi.com</a></p>
	</div>
</template>

7. 重新启动项目

然后在执行 npm run dev 刷新下浏览器, 就可以看到天气接口请求成功了!

附天气api传参文档
参数名必选类型说明备注(示例)
appidstring用户appid
appsecretstring用户appsecret
cityidstring城市ID请参考 城市ID列表
citystring城市名称不要带市、区、县; 如: 青岛、铁西、梁山
provincestring所在省防止city重名, 不要带省; 如: 山东、上海、广西
ipstringIP地址查询IP所在城市天气
lngString经度如: 119.545023 (需额外开通lbs权限)
latString纬度如: 36.044254
pointString坐标体系默认百度坐标, 如使用高德坐标, 请传参: gaode
callbackstringjsonp参数如: jQuery.Callbacks
vuestring跨域参数如果您使用的是react、vue、angular请填写值: 1
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值