由于在vue3 setup中已经没有了this,所以this.$refs 自然是不能使用的,但是vue3 还给我们预留了一个api,那就是getCurrentInstance,我们可以通过声明定义的方式,替换this。
TypeScript
<script setup>
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
const childRef = instance.ctx.$refs.bzhlcEcharts.initChart()
</script>
但是我这里主推的不是这种方法,因为这类写法在 Vue 3 里不稳定,尤其是在 <script setup> 里,ctx 也不是推荐用法。
最稳妥的方式是:用 ref 绑定子组件实例,然后直接 .value 调方法,也就是:
TypeScript
<template>
<lineChart ref="trendChart" class="chart-container"></lineChart >
</template>
<script setup lang="ts">
import { ref } from "vue"
import lineChart from './lineChart .vue'
const trendChart= ref<any>(null)
trendChart.value?.initChart();
</script>
效果:
