在三元运算符中使用多个条件时,我的 Vue 应用程序无法加载

My Vue App doesn't load on using multiple conditions in ternary operator

在一个天气显示应用中我曾经学习过Vue 这是应用程序正常运行的原始表达式

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp < 16 ? '' : 'warm' ">

但是当我将表达式更改为 -

<div id="app" :class="typeof weather.main != 'undefined' && weather.main.temp < 16 ? '' : weather.main.temp < 18 ?'chill': weather.main.temp < 30 ?'warm':'hot' ">

应用程序编译但未加载任何内容,控制台为空白,没有错误。

问题是operator precendece。表达式被计算为

(typeof weather.main != 'undefined' && weather.main.temp < 16) ? '' : (weather.main.temp < 18 ?'chill': weather.main.temp < 30 ?'warm':'hot')

这导致在 weather.main 未定义时计算 weather.main.temp < 18

解决方案是不要将不可读的代码放入模板中,而是将其移动到计算的 属性 中,以便以易于理解和维护的形式编写。 typeof 只有潜在未定义的变量才需要检查未定义的值。可选链接可用于 Vue 2 中的计算属性以避免条件检查,以及 Vue 3 中的模板。

可以是:

computed: {
  appClass() {
    if (!weather.main || weather.main.temp < 16)
      return '';
    else if (weather.main.temp < 18)
      return 'chill';
    else if (weather.main.temp < 30)
      return 'warm';
    else 
      return 'hot';
  }
}