jeudi 18 octobre 2018

Adding rows and columns to a table dynamically using vue js

I am trying to implement a feature where a user would be able to add new columns and rows to a table using vue js. I am able to push a tag to the table however the method I'm using to add the I don't think its the right way especially since the td's are being added to the object but only to the view itself.

I am pulling the default html table content from laravel's helper file

 (object)array(
        'label'         => 'Table', 
        'field_name'    => '', 
        'type'          => 'table',
        'properties'    => (object)array(
            'headers' => [
                'Header 1',
            ],
            'rows' => [
                (object) array(
                    'value' => 'Row 1 content',
                ),
            ],
        )
    )

Html(vue js)

...
<div v-if="field.type == 'table'">
   <pre></pre><br>
   <pre></pre>
   <table :class="`table ` + field.properties.style" :id="`table`+index">
         <thead>
            <tr>
               <th v-for="(header, index) in field.properties.headers" v-if="header.length > 0">
                    
                   <a href="#" title="Remove Column" @click.prevent="removeTableColumn(field.properties, index)"><i class="fa fa-trash"></i></a>
               </th>
           </tr>
        </thead>
        <tbody>
           <tr v-for="(row, index) in field.properties.rows" :key="index" id="default-row">
               <td></td>
           </tr>
        </tbody>
    </table>
    <table>
        <tr>
           <td>
              <a href="#" class="btn btn-sm btn-add-page" @click.prevent="addTableColumn(field.properties, index)">Add Column</a>
              <a href="#" class="btn btn-sm btn-add-page" @click.prevent="addTableRow(field.properties, index)">Add Row</a>
           </td>
           <td></td>
           <td></td>
         </tr>
    </table>
</div>
...

Script(vue js)

...
methods: {
    addTableColumn(properties, index) {
        properties.headers.push('Column Heading');
        $(`#table${index} #default-row`).append(`<td>Row Content</td>`);
    },
    removeTableColumn(properties, index) {
        properties.headers.splice(index, 1);
        properties.rows.splice(index, 1);
    },
    addTableRow(properties, index) {
        // let columnCount = properties.headers.length;

        // for(let i = 0; i < columnCount; i++) {
        //     properties.rows.push({'value': 'Row content'});
        // }
        // console.log(columnCount);
        // console.log(index);
        // rows.push({ 'value': 'Row column' });

        $(`#table${index}`).append(`<tr>${$('#default-row').html()}</tr>`);
    }
},...

View As seen in the picture below, I clicked the "add column" button and only the heading itself is pushed to the array and not the new td content(Row content). enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire