【问题标题】:Conditional statement not working on a VueJs method条件语句不适用于 VueJs 方法
【发布时间】:2019-08-20 23:07:09
【问题描述】:

我正在尝试添加条件语句,所以当用户切换按钮时会触发一个动作,例如输出一些文本。

我尝试将条件添加为方法,并将其添加为计算属性但没有成功,我也尝试使用 switch 语句。

我会添加codepen链接https://codepen.io/manosx/pen/KELmpj?editors=0010

  clickedTag: function (indexTag) {
      // toggle the active class
      this.$set(this.isClickedTag, indexTag, !this.isClickedTag[indexTag])
      let tagsSelected = _.keys(_.pickBy(this.isClickedTag, _.identity))
      let tagsSelectedSingle = tagsSelected.map(s => `'${s}'`).join(', ')
      console.log(tagsSelectedSingle)
      if (tagsSelectedSingle === '0') { console.log('naylon') }
      else if (tagsSelectedSingle === '1') { console.log('espiga') }
      else if (tagsSelectedSingle === '2') { console.log('omega') }
      else if (tagsSelectedSingle === '3') { console.log('crochet') }
      else if (tagsSelectedSingle === '4') { console.log('thread') }
      else if (tagsSelectedSingle === '5') { console.log('bordado') }
    },

我想添加一个条件语句,根据打开的按钮触发不同的操作。

【问题讨论】:

  • 那么,你要问的是放一些其他代码而不是console.log?您可以在这些块中放置任何内容,调用您喜欢的任何函数...所以mySuperSpecialFunction('naylon') 而不是console.log('naylon') - 那么您需要做的就是创建mySuperSpecialFunction 来做您需要它做的事情(这是模糊的在你的问题中)
  • 不是If语句不起作用,console.log输出的任何东西都不能输出
  • 好吧,tagsSelectedSingle = tagsSelected.map(s => '${s}').join(', ') 建议 tagSelectedSingle 根本不是一个值 - 所以,也许你需要将它保存为一个数组,并使用 tagSelectedSingle.includes('1')

标签: javascript arrays methods vuejs2 frontend


【解决方案1】:

最好使用indexOf(),因为包含在某些浏览器上不起作用。

试试这个。

if (tagsSelectedSingle.indexOf('0')>=0) { console.log('naylon') }
           if (tagsSelectedSingle.indexOf('1')>=0) { console.log('espiga') }
           if (tagsSelectedSingle.indexOf('2')>=0) { console.log('omega') }
           if (tagsSelectedSingle.indexOf('3')>=0) { console.log('crochet') }
           if (tagsSelectedSingle.indexOf('4')>=0) { console.log('thread') }
           if (tagsSelectedSingle.indexOf('5')>=0) { console.log('bordado') } 

【讨论】:

  • 它部分工作,例如,当我打开第一个按钮时,它将输出“espiga”,除非我停用第一个按钮,否则所有后续按钮的结果都会保留。我想为按钮上的其余操作独立输出每个按钮的结果。
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多