2017-10-17 35 views
1

我正在尝试构建一个html,我可以添加新行,然后执行批量上传到laravel并将所有项目从数据库中插入。VueJS和Laravel从html <table>获取数据并执行批量上传到laravel

表看起来是这样的:

<div id="app"> 
<table class="table"> 
    <thead> 
    <tr> 
     <td><strong>Name</strong></td> 
     <td><strong>Job</strong></td> 
     <td></td> 
    </tr> 
    </thead> 
    <tbody> 
    <tr v-for="row in rows"> 
     <td><input type="text" v-model="row.name"></td> 
     <td><input type="text" v-model="row.job"></td> 
     <td><a @click="removeRow(row)">Remove</a></td> 
    </tr> 
    </tbody> 
</table> 
<div> 
    <button class="button btn-primary" @click="addRow">Add row</button> 
</div> 
</div> 

var app = new Vue({ 
    el: "#app", 
    data: { 
    rows: [ 
     {name: "James Bond",job: "spy"}, 
     {name: "Goldfinger", job: "villain"} 
    ] 
    }, 
    methods:{ 
    addRow: function(){ 
     this.rows.push({name:"",job:""}); 
    }, 
    removeRow: function(row){ 
     //console.log(row); 
     this.rows.$remove(row); 
    } 
    } 
}); 

演示:https://jsfiddle.net/7nxhygLp/

比方说,我在现在又增加了20个项目我要发布这些数据laravel并插入在所有20个项目同时。

那么如何从我使用vueJS获取数据,以及如何在我的控制器中解析它以执行批量上传?

+0

它们位于Vue实例的“rows”字段中。因此,要么创建一个新的方法'sendRows'来访问'this.rows'并上传使用您选择的XHR库,或者从外部访问'app.rows'。 – Botje

回答

0

检查此琴:https://jsfiddle.net/7nxhygLp/282/

<div id="app"> 
<table class="table"> 
    <thead> 
    <tr> 
     <td><strong>Name</strong></td> 
     <td><strong>Job</strong></td> 
     <td></td> 
    </tr> 
    </thead> 
    <tbody> 
    <tr v-for="row in rows"> 
     <td><input type="text" v-model="row.name"></td> 
     <td><input type="text" v-model="row.job"></td> 
     <td><a @click="removeRow(row)">Remove</a></td> 
    </tr> 
    </tbody> 
</table> 
<div> 
    <button class="button btn-primary" @click="addRow">Add row</button> 
    <button class="button btn-primary" @click="submitRows">Submit rows</button> <!-- Add this --> 
</div> 
</div> 

var app = new Vue({ 
    el: "#app", 
    data: { 
    rows: [ 
     {name: "James Bond",job: "spy"}, 
     {name: "Goldfinger", job: "villain"} 
    ] 
    }, 
    methods:{ 
    addRow: function(){ 
     this.rows.push({name:"",job:""}); 
    }, 
    removeRow: function(row){ 
     //console.log(row); 
     this.rows.$remove(row); 
    }, 
    submitRows: function() { // add the action 
     axios.post('/api/link/here', rows) 
     .then((response) => { 
      console.log(response) 
     }) 
    } 
    } 
}); 

然后,在你的控制器,遍历数组并保存到数据库:

foreach ($request['rows'] as $row) { 
    [*addClassHere*]::create($row); 
} 

这是我做到了。