這篇文章主要介紹了如何解決vue中父組件向子組件echarts傳值問題,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
問題:當父組件傳值給子組件echarts時,發現子組件獲取的props為空,剛開始以為是鉤子函數放錯了地方,后來發現從mounted和created都不行。當在父組件data定義傳遞的數據的時候子組件顯示正常
原因:后來經過排查,此處省略N字,發現echarts是在渲染的時候就傳遞數據
解決方案:在父組件定義一個flag,當數據獲得的之后再進行子組件的渲染
//父組件
<p class="chart-wrapper">
<pie-chart v-if="flag" :pie-data="piedata"></pie-chart>
</p> ...
export default {
name: 'device',
data() { return {
flag:false,
piedata:{}, ...
},
created(){
this.init()
},
methods:{
init(){
axios.get('/static/mock/status/pie.json').then(this.getInfoSucc)
},
getInfoSucc(res){
res = res.data; if(res.code ==0){
const values = res.values;
this.piedata = values.piedata;
this.flag = true
}
}//子組件<template>
<p :class="className" :style="{height:height,width:width}"></p></template><script>import echarts from 'echarts'require('echarts/theme/macarons') // echarts themeimport { debounce } from '@/utils'export default {
props: {
pieData: {
type: Object
},
msg: {
type:Number
},
className: {
type: String, default: 'chart'
},
width: {
type: String, default: '100%'
},
height: {
type: String, default: '300px'
}
},
data() { return {
chart: null
}
}, // watch: {
// piedata: {
// deep: true,
// handler(val) {
// console.log(val)
// this.setOptions(val)
// }
// }
// },
mounted() {
console.log("pieData:"+JSON.stringify(this.pieData)) this.initChart() this.__resizeHanlder = debounce(() => { if (this.chart) { this.chart.resize()
}
}, 100)
window.addEventListener('resize', this.__resizeHanlder)
},
beforeDestroy() { if (!this.chart) { return
}
window.removeEventListener('resize', this.__resizeHanlder) this.chart.dispose() this.chart = null
},
methods: {
setOptions({ text, arrtype, arrdata } = {}) {
this.chart.setOption({
title: {
text: text
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/> : {c} ({d}%)'
},
legend: {
left: 'center',
bottom: '10',
data: arrtype
},
calculable: true,
series: [
{
name: '',
type: 'pie',
roseType: 'radius',
radius: [15, 95],
center: ['50%', '42%'],
data: arrdata,
animationEasing: 'cubicInOut',
animationDuration: 2600
}
]
})
},
initChart() { this.chart = echarts.init(this.$el, 'macarons') this.setOptions(this.pieData);
}
}
}</script>然后子組件就能正常顯示了 
感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何解決vue中父組件向子組件echarts傳值問題”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。