vue.js - 基于 props 的 Vue 切换类
问题描述
我正在尝试根据isNight
的真值切换一个类:
<div :class="['app-bg', { nightBg: isNight }]"></div>
我将isNight
道具设置为 false,如图所示:
export default {
name: 'Result',
data(){
return {
error: null,
weather: null,
weatherIcon: null,
isNight: false
}
},
. . .
我有一个计算函数,它根据一些数据返回真或假:
computed: {
nightChecker() {
return this.weatherIcon.slice(2) == 'n' ? true : false
}
},
如何更新isNight
道具以反映 的返回值nightChecker()
?我试过isNight: nightChecker
了,但这会引发错误。
编辑:感谢所有帮助我更了解这一点的人。正如你所知道的,我是 Vue 的新手,并且还在纠结于它。
解决方案
假设错误是从weatherIcon
开始null
的,那是因为null
没有slice
方法。slice
反正你不需要。
slice
返回一个范围,但由于您只针对 1 个字符进行测试,因此评估索引更有意义- 通过不使用
slice
,即使weatherIcon
是null
- 正如评论中提到的,三元是不必要的,您可以返回相等检查的值
computed: {
nightChecker() {
return !!this.weatherIcon && this.weatherIcon[2] === 'n';
}
}
双重 not是必要的,因为is null && false
, null
notfalse
如果这仍然不清楚,这是一个演示:
new Vue({
el: "#app",
data() {
return {
weatherIcon: null
}
},
computed: {
nightChecker() {
return !!this.weatherIcon && this.weatherIcon[2] === 'n';
}
},
methods: {
toggle() {
this.weatherIcon = this.weatherIcon === 'tonight' ? 'today' : 'tonight'
}
},
});
<div id="app">
Is it night? {{ nightChecker }} <br>
<button @click="toggle">Toggle day/night</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
推荐阅读
- python - 如何为 geoalchemy2 类型使用 SQLAlchemy @compiles 装饰器
- visual-studio-2017 - 更新 nuget 包后,Web.Config 中的程序集指令重复
- reactjs - 具有 useEffect 依赖项的无休止 XHR 请求
- python - Python归一化线性模型产生奇怪的结果
- asp.net-mvc - 跨 MVC、WebAPI 和 WebForms 共享同一个 Unity 容器?
- javascript - 在验证器中快速返回未定义
- c - 修复异常原因后 GDB 恢复执行
- sql - 查询性能问题(WHERE 字段 IN 数组)
- python - AttributeError:“学生”对象没有属性“calculateGrade”
- gradle - Checkstyle gradle 使用谷歌检查