Kanagaraj Subramaniam
Kanagaraj Subramaniam

Reputation: 35

How to use Vue.js variable/parameter inside v-if condition

I need to pass a dynamic variable into v-if attribute. I tried multiple ways but it doesn't produce the expected result.

So far, I have this: v-if="customDropdown === {{row.name}}"

How can I conditionally and dynamically render the element, please? Thank you in advance.

Upvotes: 3

Views: 23734

Answers (4)

Dawid Zbiński
Dawid Zbiński

Reputation: 5826

You cannot use interpolation in Vue directives/attributes.

To bind to v-if or v-for use variables directly:

<div v-if="value.someProperty"></div>

To bind to other attributes/properties use v-bind: or shorthand : as follows:

<div :directive="value"></div>

Template Syntax documentation

Upvotes: 2

Jean Bonilha
Jean Bonilha

Reputation: 11

First, you cannot interpolate directives/attributes and second, it's not clear, but I think you want to check the condition while iterating by a array.

You can use the template structure below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
    v-for="row in arrayList"
    v-if="customDropdown === row.name"
    >
    Show row content: {{ row }}
  </div>
</div>

With the data structure below to achieve you goal:

new Vue({
  el: '#app',
  data: {
    customDropdown: 'first',
    arrayList: [
      {
        name: 'first',
      },
      {
        name: 'second',
      },
     ],
  },
})

Upvotes: 1

Taqi Vaheed
Taqi Vaheed

Reputation: 112

You need binding the row.name to data object in vue:

export default { data() { return { customDropdown: 'something', row: {name: 'something'}, } } }

and then use it in the v-if statement:

<div v-if="customDropdown == row.name">You see me if customDropdown is equal to row.name</div>

Upvotes: 1

niclas_4
niclas_4

Reputation: 3674

Just use the properties name,

For example

export default {
 data() {
    return {
       var: true 
     }
  }
}

html

<span v-if="var">I only appear when the condition is true</span>

Upvotes: 0

Related Questions