当前位置:首页 > 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为例:

vue实现天气小案例

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文件,包含模板、脚本和样式。

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创建一个新项目,确保已安装Node.js和Vue CLI。 vue create fruit-list cd fruit-list npm…

vue实现页面各种案例

vue实现页面各种案例

Vue 实现页面常见案例 动态表单生成 使用 v-for 和 v-model 动态渲染表单字段,适合问卷或配置类场景。通过数据驱动表单结构,字段类型可扩展为输入框、下拉框等。 <templat…

css天气制作

css天气制作

CSS天气动画制作 使用CSS可以创建简单的天气动画效果,如晴天、雨天、雪天等。以下是几种常见天气效果的实现方法: 晴天效果 通过径向渐变和动画制作太阳发光效果: .sun { width:…

php实现天气

php实现天气

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

js日历案例实现

js日历案例实现

实现基础日历功能 日历功能可以通过JavaScript结合HTML和CSS实现,核心是动态生成日期表格。以下代码展示了一个基础的日历生成器: function generateCalendar(ye…

uniapp的案例

uniapp的案例

常见 Uniapp 案例类型 Uniapp 的案例覆盖多个领域,包括电商、社交、工具类应用等。以下是一些典型场景: 电商平台 跨端商城:支持微信小程序、H5、App,实现商品展示、购物车、…