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>

效果:

相关推荐
FungLeo1 小时前
成为全栈·React 管理后台篇·总复盘:从“接口能调通”到“后台值得使用”
前端·react.js·前端框架·项目复盘·成为全栈
Csvn2 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_2 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt2 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
JavaGuide4 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel4 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
莪_幻尘5 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm
风骏时光牛马5 小时前
AI模型综合能力评测:性能、指令遵循与多场景实测对比
前端
Frag0ut5 小时前
Chrome与Chromium内核浏览器在Windows 11上的新特性全景解析
前端·chrome·windows·web安全·chromium·gemini ai·playready drm
hiahiahia1236 小时前
实现完整 Tool Dispatcher
开发语言·前端