CodeName
CodeName

Reputation: 579

using a v-if inside a v-for

I have 2 datasets (dataset A and dataset B) that contain various information, and I am using a v-for to generate table rows dynamically based on the length of dataset A.

However, I am now trying to use a v-if inside the v-for to check if the id column in dataset A matches the id column in dataset B. If it does, then I will display the Available button, else I will display the Unavailable button.

However, I understand the v-if does not work in v-for. Thus, is there alternative ways to go about this situation?

Here's my code sample:

<tr v-for="(dataset, i) in datasetA" :key="i">
     <td v-if="checkIfSame(dataset['id']) == true">
          <button class="btn btn-primary" :id="dataset['id']">
             Available
          </button>
    </td>
   <td v-else>Unavailable</td>
</tr>

Inside my methods: {}:

checkIfSame: function (id) {
    this.datasetB.filter(function (item) {
        return item.id === id;
    });
},

Upvotes: 1

Views: 670

Answers (1)

steve16351
steve16351

Reputation: 5812

The code you have should be fine.

It is not recommended to use v-for and v-if on the same node. For example, if you had this, that is not recommended:

<tr v-for="(dataset, i) in dataSetA" :key="i" v-if="checkIfSame(dataset['id']) == true">
    <td>etc.</td>
</tr>

The reason being that v-for has a higher precedence than v-if. In that case, better to use a computed property to return the filtered list.

What you have in your example is:

<topLevelEl v-for="i in z">
    <childEl v-if="i === 2">
        It's two!
    </childEl>
    <childEl v-else>
        It's not two.
    </childEl>
</topLevelEl>

The v-if and v-for are not on the same node here. v-if is on childEl and v-for is on topLevelEl. This is fine. Anything except the node with v-for on is fine. You can still use it on the same HTML tag again if it's nested within, so for example if you had topLevelEl nested again inside, you're still free to use it on that, too.

Upvotes: 1

Related Questions