首页 > 解决方案 > 使用vue js动态向表中添加行和列

问题描述

我正在尝试实现一个功能,用户可以使用 vue js 向表中添加新的列和行。我可以将标签推送到表中,但是我用来添加标签的方法我认为它不是正确的方法,特别是因为 td 被添加到对象中,而只是添加到视图本身中。

我正在从 laravel 的帮助文件中提取默认的 html 表格内容

 (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>{{field.properties.headers}}</pre><br>
   <pre>{{field.properties.rows}}</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">
                   {{header}} 
                   <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>{{row.value}}</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>
...

脚本(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>`);
    }
},...

查看如下图所示,我点击了“添加列”按钮,只有标题本身被推送到数组中,而不是新的 td 内容(行内容)。 在此处输入图像描述

标签: laravel-5vuejs2

解决方案


推荐阅读