实现一个简易的天气查询应用:Vue3与API的完美结合

实现一个简易的天气查询应用:Vue3与API的完美结合

在现代前端开发中,Vue.js 作为一个流行的框架,因其简单易用和强大的功能而受到开发者的广泛欢迎。特别是 Vue 3,凭借其引入的 Composition API(组合式 API),让我们在组织和复用代码方面有了更大的灵活性。本文将带领大家通过一个简易的天气查询应用来探索 Vue 3 和 API 的完美结合。

项目概述

本项目将使用 Vue 3 和一个公共天气 API(例如 OpenWeatherMap)来构建一个简单的天气查询应用。用户可以在输入框中输入城市名,点击查询按钮后,应用将显示该城市的当前天气情况。

准备工作

在开始之前,确保你已经安装了 Node.js 和 Vue CLI。请在命令行中运行以下命令来创建一个新的 Vue 3 项目:

vue create weather-app

选择 Vue 3 配置,并进入项目目录:

cd weather-app

然后安装 axios,这是一个用于处理 HTTP 请求的库:

npm install axios

接下来,你需要从 OpenWeatherMap 注册一个账号并获取 API 密钥。

项目结构

接下来,我们将项目结构设置为以下样子:

weather-app/
├── src/
│   ├── components/
│   │   └── Weather.vue
│   ├── App.vue
│   ├── main.js

创建 Weather 组件

让我们在 src/components 目录中创建一个名为 Weather.vue 的组件,负责处理天气查询的逻辑和渲染。

<template>
  <div class="weather-container">
    <h1>天气查询应用</h1>
    <input v-model="city" type="text" placeholder="请输入城市名" />
    <button @click="fetchWeather">查询天气</button>

    <div v-if="weatherData">
      <h2>{{ weatherData.name }} 的天气</h2>
      <p>温度: {{ Math.round(weatherData.main.temp - 273.15) }} °C</p>
      <p>天气: {{ weatherData.weather[0].description }}</p>
      <p>湿度: {{ weatherData.main.humidity }} %</p>
      <p>风速: {{ weatherData.wind.speed }} m/s</p>
    </div>

    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';

export default {
  name: 'Weather',
  setup() {
    const city = ref('');
    const weatherData = ref(null);
    const error = ref(null);
    
    const apiKey = 'YOUR_API_KEY'; // 替换为你的 API 密钥

    const fetchWeather = async () => {
      if (!city.value) {
        error.value = '请输入城市名!';
        return;
      }

      error.value = null;
      
      try {
        const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city.value}&appid=${apiKey}`);
        weatherData.value = response.data;
      } catch (err) {
        error.value = '无法获取天气数据,请检查城市名称是否正确。';
        weatherData.value = null;
      }
    };

    return {
      city,
      fetchWeather,
      weatherData,
      error,
    };
  }
};
</script>

<style scoped>
.weather-container {
  max-width: 400px;
  margin: 0 auto;
  text-align: center;
  background-color: #f0f0f0;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

input {
  padding: 10px;
  width: 80%;
  margin-bottom: 10px;
}

button {
  padding: 10px 20px;
}
.error {
  color: red;
  margin-top: 10px;
}
</style>

修改 App.vue

接下来,我们在 src/App.vue 中引入和使用 Weather 组件:

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

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

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

<style>
body {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  background-color: #eaeaea;
}
</style>

运行应用

在命令行中输入以下命令以启动开发服务器:

npm run serve

打开浏览器,访问 http://localhost:8080,你会看到一个简洁的天气查询应用。输入城市名后,点击查询按钮,你将获得该城市的实时天气信息。

代码解释

  1. 组合式 API:在 Weather.vue 中,我们使用 ref 来创建响应式变量。city 用于存储用户输入的城市名,weatherData 存储从 API 获取的天气数据,error 用于处理错误信息。

  2. fetchWeather:这个 async 函数负责发起请求并处理响应。在请求前,它会检查用户是否输入了城市名;如未输入,将提示用户进行输入。

  3. API 请求:我们使用 Axios 的 get 方法通过天气 API 获取数据。在请求完成后,根据响应来更新 weatherDataerror

  4. 样式:通过 CSS 样式设置了应用的外观,使应用看起来更加友好和美观。

结语

本文展示了如何使用 Vue 3 和 API 来构建一个简易的天气查询应用。通过使用组合式 API,我们能够更好地管理状态与逻辑,为未来的扩展和重构打下良好的基础。


最后问候亲爱的朋友们,并邀请你们阅读我的全新著作

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JJCTO袁龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值