問題描述
一次項目開發過程中,需要做一些圖表,用的是百度開源的 echarts。 vue推薦組件化開發,所以就把每個圖表封裝成子組件,然后在需要用到該圖表的父組件中直接使用。
實際開發中,數據肯定都是異步獲取的。所以我們在 mounted 生命周期中獲取數據。對vue生命周期不熟悉的,可以去看一下我之前寫一篇文章vue2.0項目實戰(4)生命周期和鈎子函數詳解
由於父組件請求的數據並不是一成不變的,會根據不同的條件請求不同的數據,此時需要圖表進行更新。
代碼示例
在父組件中
// Main.vue
<template>
<div>
...
<Pie :pieData="fullList"></Pie>
...
</div>
</template>
<script>
import Pie from 'components/SourcePie'
export default {
components: {
Pie
},
data(){
return {
fullList:{}
}
},
mounted() {
this._fullQuantity()
},
methods: {
_fullQuantity(){
// axios...
}
}
}
</script>
在父組件中,通過api接口獲得的數據傳遞給子組件。那么我們在子組件中:
// SourcePie.vue
<template>
<div style="width:300px;height:260px" id="data_source_con" v-if="pieData"></div>
</template>
<script>
import echarts from 'echarts';
export default {
name: 'dataSourcePie',
data() {
return {
//
};
},
props: {
pieData: Object
},
mounted() {
this.init()
},
methods: {
init() {
let _this = this;
this.$nextTick(() => {
var dataSourcePie = echarts.init(document.getElementById('data_source_con'));
const option = {
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)",
position: ['50%', '50%']
},
series: [{
name: '實體統計',
type: 'pie',
radius: '50%',
center: ['50%', '60%'],
data: [{
value: _this.pieData.videoNum,
name: '影視數據'
},
{
value: _this.pieData.albumNum,
name: '專輯數據'
},
{
value: _this.pieData.songNum,
name: '歌曲數據'
},
{
value: _this.pieData.novelNum,
name: '小說數據'
},
{
value: _this.pieData.presonNum,
name: '人員數據'
}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
dataSourcePie.setOption(option);
window.addEventListener('resize', function() {
dataSourcePie.resize();
});
});
}
}
};
</script>
我們發現第一次圖表能正常顯示,但是頁面一刷新或者跳轉到其它頁面,再返回到該頁面,圖表就不顯示了。
原因
自己當時沒有想那么多為什么無法加載,因此在另一個父組件進行應用的時候,他是首屏就加載,數據不變動。
但是當數據變動之后,無法自動的更新圖表。
由於 mounted 只會在掛載的時候執行一次,因此無法后續進行更新
解決辦法
通過 watch 進行圖表的更新
watch: {
pieData() {
this.$nextTick(() => {
if (this.pieData) {
this.init()
}
})
}
},
這樣就能解決我們的問題了。
如有問題,請留言
本文同步發布在 https://www.cssge.com/