首页 前端知识 实现一个最简单最基本的指定城市查询天气功能

实现一个最简单最基本的指定城市查询天气功能

2024-11-02 11:11:31 前端知识 前端哥 182 888 我要收藏

1.首先,你需要注册一个OpenWeatherMap账号,获取一个API密钥

  1. 安装axios来处理HTTP请求。

  2. npm install axios
    pnpm install axios
    yarn axios
    复制

    2.在Vue组件中使用axios发送请求并获取天气数据

    1. <div>
      <p v-if="weatherData">
      <strong>城市:</strong> {{ weatherData.name }}, {{ weatherData.sys.country }}<br>
      <strong>温度:</strong> {{ Math.round(weatherData.main.temp) }}°C<br>
      <strong>气压:</strong> {{ weatherData.main.pressure }} hPa<br>
      <strong>湿度:</strong> {{ weatherData.main.humidity }} %<br>
      <strong>天气:</strong> {{ weatherData.weather[0].description }}
      </p>
      <p v-else>
      加载中...
      </p>
      </div>
      复制
    ts代码
  3. import { onMounted, ref } from 'vue'
    import axios from 'axios'
    const weatherData = ref(null)
    onMounted(async () => {
    try {
    const apiKey = 'APIKEY' // 替换为你的API密钥
    const url = `http://api.openweathermap.org/data/2.5/weather?q=安康&appid=${apiKey}&units=metric`
    const response = await axios.get(url)
    weatherData.value = response.data
    }
    catch (error) {
    console.error('Error fetching weather:', error)
    }
    })
    复制

转载请注明出处或者链接地址:https://www.qianduange.cn//article/19810.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!