如圖:需求分析
父組件是頁面,顯示表格數據,子組件是一個功能和信息欄,主要是添加信息的表單以及記錄表格數據條數。子組件如何獲取父組件數據條數呢?
使用computed計算數據長度
computed:{
total(){
let THIS=this;
let totalList=THIS.todo.length;//獲取數據長度
return totalList;
},
noFinsh(){
let THIS=this;
let count=0;
THIS.todo.forEach(item=>{
if(item.status==0){
count+=1;
}
});
return count;
}
}
組件標簽中傳值:
<header-info :postChild='this.total':postNoFinsh='this.noFinsh' @handleClick='addToTable'></header-info>
子組件接收
props:{ //接收從父組件(index頁面中head-info標簽中postChild數據)
postChild:{ //數據格式
type:Number,
required:true
},
postNoFinsh:{
type:Number,
required:true
}
},
子組件顯示:
<el-row class='head_row'>
<span>總事項:</span><span>{{postChild}}</span>
<span>未完成事項:</span><span style="color:red">{{postNoFinsh}}</span>
<span>總共登入次數:</span><span>{{visitTimes}}</span>
</el-row>
子組件傳值父組件:
子組件主要把表單數據傳遞給父組件,一般提交后我們需要清空表單數據,可是這樣會導致父組件剛剛添加的數據也被清空,所以我們可以拷貝一份數據給父組件,同時將原來表單數據清空
computed:{
//使用計算屬性
formData2(){
//拷貝出一份表單數據,使用拷貝出的數據進行提交
let newObj=Object.assign({}, this.formData);
return newObj;
}
},
提交數據:
add(){
debugger;
this.formData2.date=getYMDdate(this.date);
/*注意使用父子組件通過$emit傳數據依然是一個雙向綁定過程
提交之后如果后面直接清空數據會再次觸發數據的改變,導致父組件表格數據也為空
*/
//表單驗證
if(isInt(this.formData2.importantStar)){
this.$emit('handleClick',this.formData2);
this.date='';
this.formData.importantStar='';
this.formData.text='';
}else{
alert('請輸入整數');
}
},