首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“国家”

问题描述

<template>
<div>
    <Search v-on:onSearch="onWeather"></Search>
    <div class="locationBox">
        <h1>{{weatherData.sys.country}}</h1>
        <p>{{weatherData.name}}</p>
    </div>
    <div class="weatherBox">
        <p>{{weatherData.weather.main}}℃&lt;/p>
        <p>{{weatherData.main.temp}}</p>
    </div> 
</div>

和脚本

onWeather(inputs) {
        alert(inputs);
        let fetchUrl = `${this.baseUrl}weather?q=${inputs}&units=metric&APPID=${this.apiKey}`;
        fetch(fetchUrl)
        .then((res) => {
            console.log(res);
            return res.json();
        })
        .catch((res) => {
            console.log(error);
        })
        .then((result) => {
            console.log(result)
            return this.onResult(result)
        })
    },
    onResult (results) {
        this.weatherData = results;
    },

根据响应值写得很清楚,和例子一样,但是出现了标题这样的错误。我很好奇问题是什么。如果您能提供帮助,我将不胜感激。

标签: vue.js

解决方案


您正在访问一个嵌套对象值,因此您将需要这样的东西:

<h1>{{weatherData.sys && weatherData.sys.country}}</h1>

为什么会出现错误,您可以在此处阅读。


推荐阅读