【发布时间】:2021-03-31 05:13:42
【问题描述】:
我有一个基于 Vue 的家庭 SPA。其中一个组件由v-if="isDisplayed"驱动。
这个isDisplayed是通过监听一个MQTT主题(见脚注)设置的,接收到的新消息由以下函数处理(我特别使用'hello'而不是false来确保切换到那里)。感兴趣的topic 是display_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,条件始终为假。
我的代码明显有问题,但我越看越好看。
脚注:事实上,特定协议并不重要(它是一种经常与 IoT 一起使用的总线),您可以假设 mqttMessage() 以某种方式使用参数 topic 和 message 执行都是字符串。
【问题讨论】:
-
关于脚注:您能否调试并绝对确定
message是一个字符串?喜欢console.log(typeof message)。我认为这是问题所在,您应该这样做if (message+'' === 'on')-- 将message转换为字符串。 -
@trincot:啊,你是对的。这实际上很奇怪(因此不符合 MQTT 协议 BTW):
object。当我console.log(message)我看到Uint8Array(3) [111, 102, 102]。我正在阅读有关developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 的信息。编辑; .toString() 是解决方案。您介意引导一个答案,以便我可以使用参考文献对其进行编辑并接受它吗?谢谢!
标签: javascript if-statement conditional-statements conditional-operator