deepseas
deepseas

Reputation: 133

Correct format for listing array as table rows in vue.js

I am working on this webpage where I want to display table rows based on the checkbox selection. I was able to generate working example using this question: Hide/show table rows based on checkbox

My problem is I am getting array as response instead of formatted rows. Not sure what am I missing here.

Please check the fiddle here: https://jsfiddle.net/4roe2kjq/1/

<html>
<style>

    td {
border: thin solid black;
padding-right: 10px;
padding-bottom: 5px;
padding-left: 10px;
padding-top: 5px
    }

</style>

<script src="/javascript/vue.js"></script>


 <div id="app">
      <div v-for="val in cbValues">
        <label>
          <input type='checkbox' :value='val' v-model="selectedType"> 
          {{val}}
        </label>
      </div>
      <table>
      
      
        <template v-for="c in staff_member">
    


              <tr v-if="isVisible(c)">
               <td>{{c.courses}}</td>
            </tr>


  
        </template>
        
        </table>

<script>


   new Vue({
      el: '#app',


      data: {

        selectedType: [],
           staff_member:[{
   
      description :'Non-lab Staff Member',
    courses:[
      {course :'first'},
      {course :'second'}

    ]

  }],
  
  
  
        cbValues: [
        'Non-lab Staff Member'
        ]
      },
      methods: {
        isVisible(row) {
           const matchedValue = this.cbValues.find(v => row.description.indexOf(v) >= 0);
          if (!matchedValue) {
            return true;
          }
          return this.selectedType.includes(matchedValue);
        }
      }
    });

</script>

Upvotes: 0

Views: 552

Answers (1)

Giovane
Giovane

Reputation: 1451

As I could understand, you want to show a table of courses depending on the selection of staff members, right?

You are displaying an array of courses because you aren't iterating the staff's courses array, you are only iterating the staffs and displaying the courses raw value.

A quick refactoring in your code, would look something like this:

...
  <table>
    <template v-for="(staff, key2) in staff_member" :key="key2">
      <template v-if="isVisible(staff)">
        <tr v-for="(course, key3) in staff.courses" :key="key3">
          <td>{{course.course}}</td>
        </tr>
      </template>
    </template>
  </table>

Besides iterating over the staffs, you should iterate over the staff's courses.

Something important that you should use is the key attribute whenever you use v-for, take a look at the docs

Upvotes: 1

Related Questions