首页 > 解决方案 > 基于 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 的新手,并且还在纠结于它。

标签: vue.js

解决方案


假设错误是从weatherIcon开始null的,那是因为null没有slice方法。slice反正你不需要。

  • slice返回一个范围,但由于您只针对 1 个字符进行测试,因此评估索引更有意义
  • 通过不使用slice,即使weatherIconnull
  • 正如评论中提到的,三元是不必要的,您可以返回相等检查的值
computed: {
  nightChecker() {
    return !!this.weatherIcon && this.weatherIcon[2] === 'n';
  }
}

双重 not是必要的,因为is null && false, nullnotfalse

如果这仍然不清楚,这是一个演示:

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>


推荐阅读