Problem:
When the dialog box (Dialog) contains sub-components, we use this.$refs to try to obtain the dom of the component and operate it, and we find that the obtained dom is undefined, which causes the subsequent method to report an error;
<template>
<div>
<el-dialog :visible.sync="propertyDialog" width="60%" center>
<lineChart
ref="chart"
:xAxisArr="xAxisArr"
:yAxisArr="yAxisArr"
></lineChart>
</el-dialog>
</div>
</template>
<script>
import lineChart from "@/components/lineChart.vue";
export default {
data() {
return {
xAxisArr: [],
yAxisArr: [],
propertyDialog: false,
};
},
components: {
lineChart,
},
methods: {
showCharts() {
this.propertyDialog = true;
console.log(this.$refs.chart);
this.$refs.chart.drawLineChart();
},
},
};
</script>
Solution:
Because I have used refs to call sub-component methods before, but I haven't encountered this kind of problem, I feel helpless and hesitate.
Later, I wandered around in Du Niang's arms and discovered that it had something to do with the element-ui framework. In short, I can't tell what the relationship is.
Just add a this.$nextTick , the meaning of this callback function, in fact, the simple understanding is: wait for all the DOM element nodes to be rendered before executing the methods in it.
What do you mean specifically, please refer to the principles and usage of $nextTick() and Vue.nextTick() in Vue
showCharts(params) {
this.propertyDialog = true;
this.$nextTick(()=>{
console.log(this.$refs.chart);
this.$refs.chart.drawLineChart();
})
},