如何根据某些条件将类绑定到div,其中条件不仅仅基于使用Vue.js的true或false条件?

时间:2017-09-06 14:14:15

标签: css vue.js

实际上,我需要根据用户给出的具体值激活div的背景颜色。所以我做了类似的事情。而且不知道该怎么走。

<template>
    <div>
            <div class="row" style="padding-left:6vw; padding-right:6vw;">
                <button @click="r_id = 1"><q-icon name="thumb_up" class="reaction col-auto" style="font-size: 3rem;" /></button>
                <button @click="r_id = 2"><q-icon name="ion-happy" class="reaction col-auto" style="font-size: 3rem;" />   </button>     
                <button @click="r_id = 3"><q-icon name="ion-ios-heart" class="reaction col-auto" style="font-size: 3rem;" />  </button>     
                <button @click="r_id = 4"><q-icon name="ion-sad" class="reaction col-auto" style="font-size: 3rem;" /></button>
                <button @click="r_id = 5"><q-icon name="thumb_down" class="reaction col-auto" style="font-size: 3rem;" /></button>
           </div>
          <div class="button-group">
                    <q-btn class="button" push color="amber-7" style="width: 75px" @click="Reset()">Reset</q-btn>
                    <q-btn class="button" push color="positive" style="width: 75px" @click="Submit()">Submit</q-btn>
          </div>
    </div>
    <div v-bind:class="[{active1: r_id === 1},{active2: r_id === 2},{active3: r_id === 3},{active4: r_id === 4},{active5: r_id === 5}]" >
                Mycard
    </div>
<template>

我的脚本部分是:

    export default {
      components: {
        QBtn,
        QIcon
      },
      data () {
        return {
          r_id: '',
          name: '',
          toName: ''
        }
      },
      computed: {
        className () {
          return 'active' + this.r_id
        }
      },
  methods: {
    Submit: function () {
      this.hardcode = {
        'r_id': this.r_id,
        'user_name': 'Shine',
        'fb_title': this.fbTitle,
        'fb_id': this.id,
        'fb_descrption': this.fbDescription,
        'created_time': '10 hours ago',
        'user_id': '1'
      }
      this.fbList.push(this.hardcode)
      this.Reset()
      this.id++
    }
  }

我的css部分是:

active1{background:red;}
active2{background:black;}
active3{background:green;}
active4{background:yellow;}
active5{background:white;}

那么我应该如何继续使用Vuejs?

1 个答案:

答案 0 :(得分:1)

似乎r_id已经有正确的数字,所以只需使用一个简单的计算属性:

<div :class="className" >
Mycard
</div>

computed: {
    className () {
       return 'active' + this.r_id
    }
}