Home > OS >  using a v-if inside a v-for
using a v-if inside a v-for

Time:10-03

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;
    });
},

CodePudding user response:

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.

CodePudding user response:

Try like following snippet: You can change your check function to:

checkIfSame(id) {
  return this.datasetB.find(item => item.id === id) ? true : false 
},

new Vue({
  el: '#demo',
  data() {
    return {
      datasetA: [{id: 1, name: 'aaa'},{id: 2, name: 'bbb'},{id: 3, name: 'ccc'},],
      datasetB: [{id: 2, name: 'bbb'}]
    }
  },
  methods: {
    checkIfSame(id) {
      return this.datasetB.find(item => item.id === id) ? true : false
    },
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table>
    <tr v-for="(dataset, i) in datasetA" :key="i">
       <td v-if="checkIfSame(dataset.id)">
         <button class="btn btn-primary" :id="dataset.id">
           Available
         </button>
       </td>
       <td v-else>Unavailable</td>
    </tr>
  </table>
</div>

  • Related