0

I was wondering if it's possible to have a data binded v-if directive, I have an array of objects representing nav links or buttons (for login , logout ...) each of this objects has a v-if property where I define the v-if condition as a string.

From my laravel backend:

$globals['socialLinks'] = 
        [
            [ 'title' => 'facebook', 'v-if' => '$app.auth', 'icon' => 'fab fa-facebook-f', 'url' => config('app.facebook'), 'image' => '/img/social/facebook-alt-white.svg' ],
        ];

In my template (I transform this into json and pass it to my vue component template):

<div class="LAYOUTfooter9_row_container">
            <a class="LAYOUTfooter9_social_image_container" :href="social.url" v-for="(social,index) in $app.globals.socialLinks" v-if="[social.v-if]" :key="index+'S'">
                <img class="LAYOUTfooter9_social_image" :src="social.image">
            </a>
        </div>
Michal Levý
  • 33,064
  • 4
  • 68
  • 86
gabogabans
  • 3,035
  • 5
  • 33
  • 81
  • I guess you could try to eval(), although it's not a recommendable practice. What triggers my curiosity here is... is your front-end responsible to know what to display? Isn't it easier to filter your results on the back-end? – Jorge Rodríguez Dec 05 '19 at 15:09

1 Answers1

0

Execute JavaScript code stored as a string can be dangerous. Think twice if you really need it...

<a class="LAYOUTfooter9_social_image_container" :href="social.url" v-for="(social,index) in $app.globals.socialLinks" v-if="evaluateCondition(social.v-if)" :key="index+'S'">
methods: {
  evaluateCondition(condition) {
    return eval(condition)
  }
}

Your conditions have to be an expression and will be executing in the context of Vue instance so instead of $app.auth you need to use this.$app.auth

Michal Levý
  • 33,064
  • 4
  • 68
  • 86