【问题标题】:Vue JS ternary expressionVue JS 三元表达式
【发布时间】:2019-06-17 10:59:01
【问题描述】:

我正在使用 Vue JS 并尝试使用三元表达式来有条件地更改某些内容的值,我正在努力将以下内容转换为三元表达式,这是我的方法,默认情况下:isLoading是真的

fetchData(showLoading) {
  if (showLoading) {
    this.isLoading = true
  } else {
    this.isLoading = false
  }
}

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    此处不要使用条件运算符,只需将showLoading 分配给isLoading,假设您传递的是布尔值:

    this.isLoading = showLoading;
    

    如果您不一定要传递布尔值,则先转换为布尔值(如果需要):

    this.isLoading = Boolean(showLoading);
    

    如果您不得不使用条件运算符,那将是:

    this.isLoading = showLoading ? true : false;
    

    【讨论】:

    • 这就是Boolean 的用途(我个人更喜欢!!,因为它更明确)
    【解决方案2】:
    fetchData(showLoading) {
     showLoading ? (this.isLoading = true) : (this.isLoading = false)
    }
    

    【讨论】:

      【解决方案3】:

      我猜你的“showLoading”数据是布尔值,如果其他情况你不需要。

      this.isLoading = showLoading
      

      下面的代码出错了会报错

      this.isLoading = showLoading ? true : false; 
      

      【讨论】:

        【解决方案4】:

        您似乎想强制 showLoading 为布尔值,所以试试这个

        this.isLoading = !!showLoading;
        

        【讨论】:

          【解决方案5】:
          this.showLoading = isLoading ? true : false;
          

          【讨论】:

            猜你喜欢
            • 2021-10-30
            • 2017-12-24
            • 1970-01-01
            • 2013-06-20
            • 1970-01-01
            • 2015-03-14
            • 2014-12-25
            • 2015-07-13
            • 1970-01-01
            相关资源
            最近更新 更多