Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
Rafael de Azeredo Avatar asked Mar 26 '26 02:03

Rafael de Azeredo


1 Answers

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

like image 152
acdcjunior Avatar answered Mar 28 '26 03:03

acdcjunior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!