3

How can I bind a property only when a variable is set to true?

<template>
    <v-list-tile :class="{[$color]: isItemSelected, [$primaryText]: isItemSelected}" :href="route">
        <v-list-tile-action>
            <v-icon :color="$primaryIcon">{{ icon }}</v-icon>
        </v-list-tile-action>
        <v-list-tile-content>
            <v-list-tile-title>{{ title }}</v-list-tile-title>
        </v-list-tile-content>
    </v-list-tile>
</template>

<script>
    export default {
        name: 'list-tile-text-icon',
        props: ['icon', 'title', 'route'],
        data: () => ({
            isItemSelected: false
        }),
        created() {
            this.isItemSelected = window.location.href === this.route;
        }
    }
</script>

On line 4 I need to bind in :color="$primaryColor" only when the isItemSelected variable is equal to true.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
Rafael de Azeredo
  • 453
  • 4
  • 8
  • 14

2 Answers2

8

The values used in v-bind are JavaScript expressions, thus you can use the Conditional (ternary) operator:

<v-icon :color="isItemSelected ? $primaryIcon : null">

Note: I'm calling it v-bind because : is just a shorthand to v-bind. I.e. :color="" is the same as v-bind:color=""

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
1

Vue class and style binding doc

this is the offical document about vue class and style binding,

detail:

<v-list-title :class="{someClassYouDefine: isItemSelected}"> </v-list-title>

then write the style you want

<style>
   .someClassYouDefine {
      color: $primaryColor;
   }
</style>
tony19
  • 125,647
  • 18
  • 229
  • 307
flypan
  • 25
  • 1
  • 9