You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue天气应用输入无效城市时显示错误消息的实现方案

Vue天气应用:无效城市错误提示实现

核心思路

  • 定义响应式变量存储错误信息
  • 调用天气API后根据返回结果判断城市是否有效(比如API返回错误码、无城市数据)
  • 根据判断结果更新错误变量,在模板中条件渲染错误提示

完整代码实现

组件模板(Template)

<template>
  <div class="weather-app">
    <div class="input-group">
      <input 
        v-model="city" 
        placeholder="输入城市名称"
        type="text"
      >
      <button @click="fetchWeather">查询天气</button>
    </div>
    <!-- 错误提示:仅当errorMessage有值时显示 -->
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    <!-- 天气信息展示(有效数据时显示) -->
    <div v-if="weatherData && !errorMessage" class="weather-info">
      <h3>{{ weatherData.cityName }}</h3>
      <p>当前温度: {{ weatherData.temp }}°C</p>
      <p>天气状况: {{ weatherData.condition }}</p>
    </div>
  </div>
</template>

脚本逻辑(Script)

<script>
export default {
  data() {
    return {
      city: '',
      weatherData: null,
      errorMessage: '' // 存储错误提示文本
    }
  },
  methods: {
    async fetchWeather() {
      // 清空上一次的错误和数据
      this.errorMessage = ''
      this.weatherData = null

      // 先做空输入校验
      if (!this.city.trim()) {
        this.errorMessage = '请输入城市名称'
        return
      }

      try {
        // 替换为真实天气API地址,这里用模拟逻辑示例
        const res = await fetch(`https://api.your-weather-service.com/query?city=${encodeURIComponent(this.city)}`)
        const data = await res.json()

        // 根据API返回规则判断是否为无效城市
        // 示例:假设API返回code=404表示城市不存在
        if (data.code === 404 || !data.result) {
          this.errorMessage = `未找到城市「${this.city}」,请检查输入是否正确`
          return
        }

        // 有效数据,更新天气信息
        this.weatherData = {
          cityName: data.result.city,
          temp: data.result.temperature,
          condition: data.result.weather
        }
      } catch (err) {
        // 处理网络错误或API异常
        this.errorMessage = '查询失败,请稍后重试'
        console.error('天气查询错误:', err)
      }
    }
  }
}
</script>

样式(Style)

<style scoped>
.weather-app {
  max-width: 400px;
  margin: 2rem auto;
  padding: 1.5rem;
  font-family: Arial, sans-serif;
}
.input-group {
  display: flex;
  gap: 0.6rem;
  margin-bottom: 1rem;
}
input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
button {
  padding: 0.5rem 1.2rem;
  background-color: #2196f3;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.error-message {
  color: #dc3545;
  padding: 0.8rem;
  background-color: #f8d7da;
  border-radius: 4px;
  margin-bottom: 1rem;
}
.weather-info {
  padding: 1rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
</style>

关键逻辑说明

  1. 响应式错误变量:errorMessage作为响应式变量,Vue会自动监听其变化并更新DOM显示
  2. 前置校验:先判断用户是否为空输入,避免无效API调用
  3. API结果判断:根据实际天气API的返回规范(比如错误码、数据字段是否存在)识别无效城市,生成对应提示文本
  4. 条件渲染:通过v-if="errorMessage"控制错误提示的显示/隐藏,只有当变量有内容时才渲染提示框

内容的提问来源于stack exchange,提问作者Parvathy Renjith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:48:19