Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add 2 condition in one class vue.js 2?

My vue component is like this :

<template>
    <a :class="'btn ' + [respond == 'responseFound' ? ' btn-yellow' : ' btn-default', type == 1 ? ' btn-block' : ' btn-xs center-block']">
       ...
    </a>
</template>

I try like that, but it does not work?

like image 693
samuel toh Avatar asked May 03 '17 12:05

samuel toh


3 Answers

You can use :class="[array, of, classes]" syntax:

<a :class="['btn', (respond === 'responseFound' ? 'btn-yellow' : 'btn-default'), (type === 1 ? 'btn-block' : 'btn-xs center-block')]">

As a bonus you don't have to worry about adding the leading spaces, Vue will handle it.

like image 58
Matt Avatar answered Sep 28 '22 06:09

Matt


Just to keep things clean in view/template/markup, move your conditions to computed properties:

<template>
  <a :class="['btn', getRespondClass, getTypeClass]">
</template>

<script>
  export default {
    data () {
      return {
        respond: '',
        type: ''
      }
    },
    computed: {
      getRespondClass () {
        return this.respond === 'responseFound' ? 'btn-yellow' : 'btn-default'
      },
      getTypeClass () {
        return this.type === 1 ? 'btn-block' : 'btn-xs center-block'
      }
    }
  }
</script>
like image 22
Syed Avatar answered Sep 28 '22 07:09

Syed


Pretty sure the current showed answer says how you can add multiple classes on 1 condition. But if you want to have multiple conditions for your class added you can simply just do it like this:

:class="{classname: condition_one && condition_two}"
like image 34
Marnix Elling Avatar answered Sep 28 '22 07:09

Marnix Elling