vue3 $refs使用方法

由于在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>

效果:

相关推荐
Java展博19 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户1129361121919 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼20 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_41920 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
去伪存真21 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li1 天前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写1 天前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
RuoyiOffice1 天前
Flowable只是起点:一套OA背后的单据、资源与协作设计
java·vue.js·spring boot·flowable·企业管理·oa·ruoyi office
TDengine (老段)1 天前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou1 天前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp