当前位置:首页 > VUE

vue实现天气查询

2026-01-15 05:48:16VUE

Vue实现天气查询功能

准备工作 确保已安装Vue CLI或通过CDN引入Vue.js。需要注册天气API服务(如和风天气、OpenWeatherMap等)获取API密钥。

项目结构

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

实现步骤

安装axios 通过npm或yarn安装axios用于API请求:

npm install axios

创建天气组件 在Weather.vue中编写核心逻辑:

vue实现天气查询

<template>
  <div class="weather-container">
    <input v-model="city" placeholder="输入城市名称" />
    <button @click="getWeather">查询</button>
    <div v-if="weatherData">
      <h3>{{ weatherData.city }}</h3>
      <p>温度: {{ weatherData.temp }}°C</p>
      <p>天气: {{ weatherData.condition }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      city: '',
      weatherData: null,
      apiKey: 'YOUR_API_KEY', // 替换为实际API密钥
      apiUrl: 'https://api.openweathermap.org/data/2.5/weather'
    };
  },
  methods: {
    async getWeather() {
      try {
        const response = await axios.get(`${this.apiUrl}?q=${this.city}&appid=${this.apiKey}&units=metric`);
        this.weatherData = {
          city: response.data.name,
          temp: Math.round(response.data.main.temp),
          condition: response.data.weather[0].main
        };
      } catch (error) {
        console.error('获取天气失败:', error);
        alert('城市不存在或查询失败');
      }
    }
  }
};
</script>

API参数说明

  • units=metric 表示使用摄氏温度
  • OpenWeatherMap的免费版API每分钟限制60次请求
  • 需要将YOUR_API_KEY替换为实际获得的密钥

样式优化 添加基础样式增强用户体验:

.weather-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

input, button {
  padding: 8px;
  margin-right: 10px;
}

button {
  background: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

错误处理增强 可扩展的错误处理方案:

vue实现天气查询

methods: {
  async getWeather() {
    if (!this.city.trim()) {
      alert('请输入城市名称');
      return;
    }

    try {
      // ...原有请求代码
    } catch (error) {
      if (error.response) {
        switch (error.response.status) {
          case 404:
            alert('城市不存在');
            break;
          case 401:
            alert('API密钥无效');
            break;
          default:
            alert('服务暂时不可用');
        }
      }
    }
  }
}

国内API替代方案 如需使用国内天气服务(如和风天气),需修改API地址和参数:

apiUrl: 'https://devapi.qweather.com/v7/weather/now',
params: {
  key: this.apiKey,
  location: this.city,
  lang: 'zh'
}

组件注册 在App.vue中引入并使用组件:

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

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

export default {
  components: { Weather }
}
</script>

注意事项

  1. API密钥应存储在环境变量中(如.env文件),避免硬编码
  2. 生产环境需考虑添加请求节流(throttle)或防抖(debounce)
  3. 可添加加载状态提示提升用户体验
  4. 部分天气API需要后端代理请求以避免CORS问题

标签: 天气vue
分享给朋友:

相关文章

vue 表格实现

vue 表格实现

Vue 表格实现方法 在 Vue 中实现表格功能可以通过多种方式完成,以下介绍几种常见的方法: 使用原生 HTML 表格 最简单的表格可以通过 Vue 模板中的原生 HTML 表格元素实现: &l…

vue实现多级组件

vue实现多级组件

实现多级组件的基本结构 在Vue中实现多级组件通常涉及父子组件嵌套,通过props向下传递数据,通过$emit向上传递事件。多级组件的核心是递归或动态组件渲染。 <!-- 父组件 Paren…

vue登录逻辑的实现

vue登录逻辑的实现

Vue 登录逻辑实现 前端实现 创建登录组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template&…

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mind…

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keywor…

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 EC…