为什么这个回调中的条件总是 returns false?

Why is the condition in this callback always returns false?

我有一个基于 Vue 的家庭 SPA。其中一个组件由 v-if="isDisplayed".

驱动

这个 isDisplayed 是通过监听 MQTT 主题设置的(见脚注),接收到的新消息由以下函数处理(我特别使用 'hello' 而不是 false 来确保开关在那里)。感兴趣的 topicdisplay_school_edt.

mqttMessage(topic, message) {
      console.log(`App.vue received topic ${topic} with payload '${message}'`)
      if (topic === "dash/reload") {
        window.location.href = window.location.href
        document.location.reload(true);
      }
      if (topic === "dash/darkmode") {
        this.nightmode = JSON.parse(message) ? "night" : "day";
      }
      // this is the part I have problems with, I left everything for completness
      if (topic === "display_school_edt") {
        console.log(`edt display received: '${message}'`);
        if (message === 'on') {
          this.isEdtDisplayed = true
        } else {
          this.isEdtDisplayed = 'hello'
        }
        // I initially went for the ternary below - same results
        // message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
        console.log(`new edt display: ${this.isEdtDisplayed}`);
      }
    }

当我发布到受监控主题 display_school_edt 时(两次:消息是 on,另一次是 off),这是我在控制台上得到的:

也就是说,无论接收到on还是off,条件总是false。

我的代码明显有问题,但我越看越好看。


脚注:具体协议并不重要(它是一种经常与 IoT 一起使用的总线),您可以假设 mqttMessage() 以某种方式使用参数 topicmessage 都是字符串。

如果message是字符串类型的话,这确实出乎意料。然而,它可能不是,而且只有你输出 message 时,你实际上将它强制转换为字符串。因此,如果您从先前的输出中看到它强制转换为“否”,那么在 if 条件下您应该执行相同的操作,并强制转换为字符串:

if (message+'' === 'no')

注意:这将调用 message.toString(),就像您在模板文字中将其引用为 ${message}.

一样