在代碼中增加一行代碼:
watch: { source (newVal, oldVal) { console.log(newVal, this.$refs.main) // [Array ...] undefined this.setOpts() } },
啟示 source 數(shù)據(jù)雖然有了,但 div 還并未掛載,因此 echarts 無(wú)法完成初始化
那么想當(dāng)然的我們就會(huì)去在 mounted 生命周期函數(shù)中調(diào)用 setOpts 方法:
mounted () { console.log(this.source, this.$refs.main) // [] undefined this.setOpts() },
這樣也是錯(cuò)的,因?yàn)槟0逭Z(yǔ)法中使用了 v-if,那么當(dāng) source 并未滿足條件的時(shí)候,div 當(dāng)然也不會(huì)掛載。因此 div 仍然無(wú)法訪問(wèn)到。
Error in mounted hook: "TypeError: Cannot read property 'getAttribute' of undefined"
解決辦法是要么去掉 v-if 要么換另一種寫(xiě)法
有時(shí)我們需要在沒(méi)有數(shù)據(jù)的情況下增加一個(gè)占位標(biāo)簽用來(lái)展示一些額外的提醒信息,如“暫未獲取到數(shù)據(jù)”等。那么去掉 v-if 肯定不行。
既然如此我們保留 v-if 但寫(xiě)法有所改變:
修改 Chart 組件:
<template> <div> <div id="main" ref="main" style="width: 600px;height: 400px;"></div> </div> </template>
我們只需要一個(gè) source 數(shù)據(jù)源,當(dāng) mounted 的時(shí)候調(diào)用 setOpts 方法,當(dāng) watch 數(shù)據(jù)變化的時(shí)候再次調(diào)用以更新數(shù)據(jù)
export default { name: 'Chart', props: ['source'], mounted () { this.setOpts() }, watch: { source () { this.setOpts() } }, methods: { setOpts () { let myChart = this.$echarts.init(this.$refs.main) myChart.setOption({ dataset: { dimensions: ['score', 'amount', 'product'], source: this.source }, xAxis: { type: 'category' }, yAxis: {}, series: [ { type: 'bar', encode: { x: 'product', y: 'amount' } } ] }) } } }
v-if 的判斷我們把他移出去了我們判斷 chartData 是否獲取到,一旦獲取到數(shù)據(jù),馬上加載 Chart 組件,這樣就可以避開(kāi)在組件內(nèi)部調(diào)用 v-if 帶來(lái)的問(wèn)題:
<template> <div> <Chart :source="chartData" v-if="flag"></Chart> <div v-else>none</div> </div> </template> import Chart from '../components/Chart' export default { name: 'Home', components: { Chart }, data () { return { chartData: [], flag: false } }, methods: { getData () { setTimeout(() => { this.chartData = [ [89.3, 58212, 'Matcha Latte'], [57.1, 78254, 'Milk Tea'], [74.4, 41032, 'Cheese Cocoa'], [50.1, 12755, 'Cheese Brownie'], [89.7, 20145, 'Matcha Cocoa'], [68.1, 79146, 'Tea'], [19.6, 91852, 'Orange Juice'], [10.6, 101852, 'Lemon Juice'], [32.7, 20112, 'Walnut Brownie'] ] this.flag = true }, 2000) } }, mounted () { this.getData() } }
另外還可將 Chart 組件和站位標(biāo)簽一同封裝成一個(gè) ChartWrapper。
這樣就不會(huì)因在組件內(nèi)部調(diào)用 watch 監(jiān)聽(tīng) props 的變化動(dòng)態(tài) v-if 判斷并掛載數(shù)據(jù)到 DOM 上出現(xiàn)的這種問(wèn)題了。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com