当前位置:首页 > VUE

vue实现天气小案例

2026-02-22 01:38:57VUE

Vue实现天气小案例

创建Vue项目

使用Vue CLI创建一个新项目,确保已安装Node.js和npm。

vue create weather-app
cd weather-app
npm install axios

获取天气API

注册并获取免费的天气API密钥,例如使用OpenWeatherMap或和风天气。以下以OpenWeatherMap为例:

const API_KEY = 'your_api_key';
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q={city}&appid=${API_KEY}&units=metric`;

创建天气组件

src/components下创建Weather.vue文件,包含模板、脚本和样式。

<template>
  <div class="weather">
    <input v-model="city" placeholder="输入城市名称" @keyup.enter="fetchWeather" />
    <div v-if="weatherData">
      <h2>{{ weatherData.name }}</h2>
      <p>温度: {{ weatherData.main.temp }}°C</p>
      <p>天气: {{ weatherData.weather[0].description }}</p>
      <img :src="`https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png`" />
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      city: '',
      weatherData: null
    };
  },
  methods: {
    fetchWeather() {
      axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${API_KEY}&units=metric`)
        .then(response => {
          this.weatherData = response.data;
        })
        .catch(error => {
          console.error('获取天气数据失败:', error);
        });
    }
  }
};
</script>

<style>
.weather {
  text-align: center;
  margin-top: 20px;
}
input {
  padding: 8px;
  margin-bottom: 10px;
}
</style>

在主组件中引入

App.vue中引入并使用Weather组件。

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

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

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

运行项目

启动开发服务器,查看效果。

npm run serve

注意事项

  • 确保替换your_api_key为实际的API密钥。
  • 处理网络请求错误,提供用户友好的提示。
  • 如果需要更复杂的UI,可以添加加载状态或更多天气信息字段。

vue实现天气小案例

标签: 天气案例
分享给朋友:

相关文章

vue实现图书管理案例

vue实现图书管理案例

Vue 实现图书管理案例 项目初始化 使用 Vue CLI 创建项目,安装必要依赖。 vue create book-management cd book-management npm inst…

用vue实现routerview案例

用vue实现routerview案例

使用 Vue Router 实现 RouterView 案例 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是一个完整的实现案例。 安装 Vue Rou…

vue实现时间天气

vue实现时间天气

以下是在Vue中实现时间和天气功能的几种方法: 获取并显示当前时间 使用JavaScript的Date对象获取当前时间,并通过Vue的数据绑定显示: <template> &l…

html css网页制作案例

html css网页制作案例

HTML CSS网页制作案例 响应式个人主页 使用HTML5和CSS3创建一个响应式个人主页,包含导航栏、简介、作品集和联系信息。通过媒体查询实现不同屏幕尺寸的适配。 <!DOCTYPE h…

css制作web天气

css制作web天气

使用CSS制作Web天气界面 基础结构设计 HTML部分需要包含天气信息的基本结构,例如城市名称、温度、天气图标和描述。以下是一个简单的HTML结构示例: <div class="weath…

php实现天气

php实现天气

使用第三方天气API实现 PHP可以通过调用第三方天气API获取天气数据。常见的免费天气API包括OpenWeatherMap、WeatherAPI、和风天气等。以下以OpenWeatherMap为例…