vue component內動態新增/刪除
by cactus77kiki
HTML
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js'></script>
<div id="app">
<h2>Todos:</h2>
<to-do-list :tot="totd" :editval = "dataVal"
ref="childobj">
</to-do-list><br/>
<button v-on:click="showdataVal">父顯示子組件資料</button><br/>
新值:{{childataval}}<br/>
<hr/>
原始:{{dataVal}}
</div>
JavaScript
/*
檔案比對:https://www.diffnow.com/report
ref:https://ru.vuejs.org/v2/examples/grid-component.html
*/
//vue component內動態新增,刪除小實驗
Vue.component('to-do-list', {
props: ['tot','editval'],
data: function () {
return {
contentVal: this.editval,
editInput:{
"seq":"",
"name":"",
"score":"",
"remark":""
}
}
},
template: `<div>
【動態新增example】
<button type="button" v-on:click="addRow">AddRow</button><br/>
<ul>
<li v-for="(row,index) in contentVal">
no:{{row.seq}}
name:<input type="text" v-model="row.name" style="width:35px;">
score:<input type="text" v-model="row.score" style="width:30px;">
remark:<input type="text" v-model="row.remark" style="width:50px;">
<button type="button" v-on:click="deleteRow(index)">刪除</button>
</li>
</ul>
</div>`,
methods:{
//刪除
deleteRow: function(index){
this.contentVal.splice(index,1);
//序號重編
if(this.contentVal){
if(this.contentVal.length>0){
var rows = JSON.parse(JSON.stringify(this.contentVal));
for(var i = 1;i<=rows.length;i++){
rows[i-1].seq = i;
}
this.contentVal = rows;
}
}
},
//新增
addRow: function(){
var rows = JSON.parse(JSON.stringify(this.contentVal));
this.resetInput();
this.editInput.seq=rows.length+1;
rows.push(this.editInput);
this.contentVal = rows;
},
//reset
resetInput: function(){
this.editInput.seq="";
this.editInput.name="";
this.editInput.score="";
this.editInput.remark="";
}
}
});
var vueapp = new Vue({
el: "#app",
data: {
dataVal: [], //餵給子組件的資料
listVal:[
{seq: '1',name: 'mark',score: '87', remark:''},
{seq: '2',name: 'lisa',score: '80', remark:'higher'},
{seq: '3',name: 'eddy',score: '65', remark:'better'}
],
...