首页 > 解决方案 > v-如果多个条件不起作用

问题描述

<template>
<div>
    <h2>{{weatherData.city}}</h2>
    <h3>{{weatherData.weather}}</h3>
    <rain-cloud v-if="iconSelect==='09d'"/>
    <sun-cloud v-if="iconSelect==='04d'"/>
    <sunshine v-if="iconSelect=='01d'"/>
    <thunder-cloud v-if="iconSelect=='11d'"/>
    <windy-cloud v-if="iconSelect=='50d'"/>
    <snow-cloud v-if="iconSelect=='13d'"/>
    <div class="container">
        <h2>{{weatherData.temperature}}°C</h2>
        <h4>max temperature: {{weatherData.tempMax}}°C</h4>
        <h4>min temperature: {{weatherData.tempMin}}°C</h4>
        <h4>humidity: {{weatherData.humidity}}%</h4>
    </div>
</div>
</template>

computed:{
        iconSelect(){
            if(this.weatherData.icon==="04n" || "04d"){
                this.weatherData.icon="04d"
            }
            else if(this.weatherData.icon==="01d"|| "01n"){
                this.weatherData.icon="01d"
            }
            else if(this.weatherData.icon==="11d"|| "11n"){
                this.weatherData.icon="11d"
            }
            else if(this.weatherData.icon==="50d"|| "50n"){
                this.weatherData.icon="50d"
            }
            else if(this.weatherData.icon==="13d"|| "13n"){
                this.weatherData.icon="13d"
            }
            else if(this.weatherData.icon==="09d"||"09n"||"10d"||"10n"){
                this.weatherData.icon="09d"
            }
            return this.weatherData.icon
 }

每个组件都是 SVG 动画。当声明为真时,我只想渲染一个。但是 v-if 不支持乘法条件。有任何想法吗?每个天气都有图标代码,例如“01d”和“01n”表示白天和晚上都很清楚。但我只能使用一个 SVG

标签: javascriptvue.js

解决方案


v-if确实支持多种条件 - 例如,假设您有:

new Vue({
  el: '#app',
  data: {
    x: 1,
    y: 2
  }
})

您将能够编写如下语句:

<div v-if="x === 1 || y === 3">
...
</div>

Vue 还提供了v-else-if="condition"v-else指令。

你的条件也有问题iconSelect()。您已按以下格式编写条件:if(this.weatherData.icon === "04n" || "04d")

此条件将始终评估为true,因为即使weatherData.icon === "04n"为 false (weatherData.icon设置为其他值),第二个表达式"04d"也会被评估 - 它评估为"04n",在条件的上下文中,它等同于true

要使这些条件按您的预期工作,它们应该采用以下格式:

if(this.weatherData.icon === "04n" || this.weatherData.icon === "04d")

或者,在您的<template>中,您需要v-if类似地更改您的条件:

<sun-cloud v-if="iconSelect === '04d' || iconSelect === '04n'"></sun-cloud>

推荐阅读