vue中子組件的methods中獲取到props中的值方法
父子組件通信
這個官網(wǎng)很清楚,也很簡單,父組件中使用v-bind綁定傳送,子組件使用props接收即可
例如:
父組件中
<template>
<div>
<head-top></head-top>
<section class="data_section">
<header class="chart-title">數(shù)據(jù)統(tǒng)計</header>
<el-row :gutter="20" class="chart-head">
<el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head blue-head">統(tǒng)計:</div></el-col>
<el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">銷售數(shù)量 <span>{{number}}</span></div></el-col>
<el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">銷售金額 <span>{{amount}}</span></div></el-col>
<el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">利潤統(tǒng)計 <span>{{profits}}</span></div></el-col>
</el-row>
</section>
<chart :chartData="chartData"></chart>
</div>
</template>
<script>
data(){
return {
number: null,
amount: null,
profits: null,
chartData: [10,10,10]
}
},
</script>
子組件中
export default {
props: ['chartData']
}
這種情況下,子組件的methods中想要取到props中的值,直接使用this.chartData即可
但是有寫情況下,你的chartData里面的值并不是固定的,而是動態(tài)獲取的,這種情況下,你會發(fā)現(xiàn)methods中是取不到你的chartData的,或者取到的一直是默認值
比如下面這個情況
父組件中
<script>
data(){
return {
number: null,
amount: null,
profits: null,
chartData: []
}
},
mounted(){
this.getStatistics();
},
methods: {
//獲取統(tǒng)計數(shù)據(jù)
getStatistics(){
console.log('獲取統(tǒng)計數(shù)據(jù)')
axios.post(api,{
}).then((res) => {
this.number = res.data.domain.list[0].number;
this.amount = res.data.domain.list[0].amount;
this.profits = res.data.domain.list[0].profits;
this.chartData = [this.number,this.amount,this.profits];
}).catch((err) => {
console.log(err);
})
},
},
</script>
此時子組件的methods中使用this.chartData會發(fā)現(xiàn)是不存在的(因為為空了)
這情況我是使用watch處理
解決方法如下:
使用watch
props: ['chartData'],
data(){
return {
cData: []
}
},
watch: {
chartData: function(newVal,oldVal){
this.cData = newVal; //newVal即是chartData
this.drawChart();
}
},
監(jiān)聽chartData的值,當它由空轉(zhuǎn)變時就會觸發(fā),這時候就能取到了,拿到值后要做的處理方法也需要在watch里面執(zhí)行
以上這篇vue中子組件的methods中獲取到props中的值方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue子元素綁定的事件, 阻止觸發(fā)父級上的事件處理方式
這篇文章主要介紹了vue子元素綁定的事件, 阻止觸發(fā)父級上的事件處理方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
vue項目使用js監(jiān)聽瀏覽器關閉、刷新及后退事件的方法
這篇文章主要給大家介紹了關于vue項目使用js監(jiān)聽瀏覽器關閉、刷新及后退事件的相關資料,文中通過代碼介紹的非常詳細,對大家學習或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

