Rafael de Azeredo
Rafael de Azeredo

Reputation: 453

VueJS Bind prop only if data variable is true

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.

Upvotes: 3

Views: 7506

Answers (2)

flypan
flypan

Reputation: 23

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>

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135752

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=""

Upvotes: 8

Related Questions