鍍金池/ 問(wèn)答/HTML/ 在vue中 三元運(yùn)算符 報(bào)錯(cuò)

在vue中 三元運(yùn)算符 報(bào)錯(cuò)

        this.$refs.checkbox.onchange = function () {
          const chk = this.checked
          const val = that.val
          if (!that.selected || typeof that.selected === 'string') {
            return that.$emit('input', chk ?  true : false)
          }
          const idx = that.selected.indexOf(val)
          if (chk) {
            that.selected.push(val)
          } else {
            that.selected.splice(idx, 1)
          }
          that.$emit('input', val)
        }

在vue中 報(bào) Unnecessary use of boolean literals in conditional expression 的錯(cuò) 請(qǐng)問(wèn)是什么原因,如何解決?還是頭一次碰到....[囧]

回答
編輯回答
玩控

that.$emit('input', !!chk);

2017年2月27日 04:18
編輯回答
怣痛

如果JavaScript預(yù)期某個(gè)位置應(yīng)該是布爾值,會(huì)將該位置上現(xiàn)有的值自動(dòng)轉(zhuǎn)為布爾值。轉(zhuǎn)換規(guī)則是除了下面六個(gè)值被轉(zhuǎn)為false,其他值都視為true:

undefined
null
false
0
NaN
""或''(空字符串)

具體實(shí)現(xiàn)可以使用樓上的代碼:

that.$emit('input', !!chk);
2017年7月8日 14:53
編輯回答
鐧簞噯

這不是vue報(bào)錯(cuò),這是eslint的規(guī)則,因?yàn)閏hk這里本來(lái)就是boolean類型的吧?
所以這么寫(xiě)是沒(méi)有必要的。

改成:

return that.$emit('input', chk)
2018年6月16日 07:27