【问题标题】:Change color of td element when clicked vue js单击vue js时更改td元素的颜色
【发布时间】:2022-01-19 14:59:06
【问题描述】:

首先填充此表时,每个文本都是灰色的并带有删除线,并且按钮被禁用。我想要的是当我单击任何特定行时,它会将颜色更改为黑色和 text-decoration:none 并仅启用该行上的按钮。

当前代码在点击任意一行时会更改每一行的颜色和文本装饰。

<table class="table table-striped">
 <tbody>
  <tr v-for="(line,index) in summary_lines_list" :key="index">
   <td><p :class="'line_'+index" v-on:click="EnableLine($event)" :style='{"text-decoration":(line_selected?"none":"line-through"),"color":(line_selected?"black":"grey")}'>{{line}}</p> </td>
   <td><button :class="'btn btn-sm btn-success line_'+index" :disabled="!line_selected">Use</button></td>
  </tr>
 </tbody>
</table>

点击方式:

methods:{
    EnableLine(event){
      this.line_selected = !this.line_selected;
    },
}

data(){
      return {
             line_selected:false
}

}

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    您应该保存所选行的索引以仅突出显示一行而不是全部

    EnableLine(index)
    

     :style='{"text-decoration":(line_selected === index?"none":"line-through"),"color":(line_selected?"black":"grey")}'
    

    对于多行选择,您需要创建数组来存储所有选择的索引。看看例子!

    new Vue({
      el: "#app",
      data: () => ({
        summary_lines_list: [
          'first line', 
          'second line',
          'third line',
          'fourth line'
        ],
        line_selected: []
      }),
      methods: {
        isSelected(index) {
          return this.line_selected.includes(index)
        },
        
        toggle: function(index){
            if(this.isSelected(index)) {
            this.line_selected.splice(this.line_selected.indexOf(index), 1)
          } else {
            this.line_selected.push(index)
          }
        },
        
        style(index) {
          const isSelected = this.isSelected(index)
          return {
            'text-decoration': isSelected ? 'none' : 'line-through',
            'color': isSelected ? 'black' : 'grey'
          }
        }
      }
    })
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <table class="table table-striped">
       <tbody>
        <tr v-for="(line, index) in summary_lines_list" :key="index">
         <td>
          <p 
            :class="'line_'+index"
            v-on:click="toggle(index)"
            :style="style(index)"
          >{{line}}</p>
         </td>
         <td>
          <button 
            class="btn btn-sm btn-success"
            :class="'line_'+index"
            :disabled="!isSelected(index)"
          >Use</button>
         </td>
       </tr>
     </tbody>
    </table>
    </div>

    【讨论】:

    • 它正在工作,但可以选择任意数量的行。目前,我只能选择一行。
    • @HemantSah 检查编辑的评论
    • 谢谢,它非常适合我。
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2016-01-14
    • 2014-12-29
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多