Vue 项目中使用$refs来访问组件实例或 DOM 元素,有哪些注意事项?

大白话Vue 项目中使用$refs来访问组件实例或 DOM 元素,有哪些注意事项?

在 Vue 项目里,$refs 是个超实用的工具,它能让你直接访问组件实例或者 DOM 元素。不过使用的时候,有一些地方可得注意,下面咱就详细唠唠。

1. $refs 只有在组件渲染完成后才可用

在 Vue 里,组件从创建到渲染完成是有个过程的。只有当组件完全渲染好了,$refs 才能正常使用。要是在组件还没渲染好的时候就想用 $refs 去访问东西,那肯定会出问题。所以,通常会把使用 $refs 的代码放到 mounted 钩子函数里,因为这个钩子函数是在组件渲染完成后才执行的。

export default {// 组件挂载完成后执行的钩子函数mounted() {// 这里可以安全地使用 $refs 访问组件实例或 DOM 元素this.$refs.myComponent.someMethod(); // 调用组件实例的方法this.$refs.myElement.focus(); // 让 DOM 元素获取焦点}
};

2. 不要在模板里直接使用 $refs

虽然 $refs 能让你访问组件实例或者 DOM 元素,但千万别在模板里直接用它。因为模板里的代码会在每次数据更新的时候重新计算,如果在模板里用 $refs,可能会导致意外的结果,而且还会影响性能。

<template><!-- 不要这样做 --><!-- <div>{{ $refs.myElement.textContent }}</div> --><div ref="myElement">这是一个 DOM 元素</div>
</template><script>
export default {mounted() {// 在 mounted 钩子函数里使用 $refsconst text = this.$refs.myElement.textContent;console.log(text); // 输出: 这是一个 DOM 元素}
};
</script>

3. $refs 不是响应式的

$refs 不像 Vue 的响应式数据那样,数据一变页面就跟着更新。$refs 只是一个普通的对象,它的属性值在组件渲染完成后就固定了。所以,如果你想在数据变化的时候更新 $refs 相关的操作,就得手动去处理。

<template><div><button @click="updateElement">更新元素</button><div ref="myElement">{{ message }}</div></div>
</template><script>
export default {data() {return {message: '初始消息'};},methods: {updateElement() {this.message = '更新后的消息';// 手动更新 $refs 相关的操作this.$refs.myElement.textContent = this.message;}}
};
</script>

4. 动态绑定 ref 时要注意

要是你需要动态绑定 ref,也就是根据不同的条件给不同的元素或者组件绑定 ref,那得小心了。因为动态绑定 ref 可能会导致 $refs 的值发生变化,所以在使用的时候要确保 $refs 里确实有你想要的元素或者组件。

<template><div><!-- 动态绑定 ref --><component :is="currentComponent" :ref="currentRef"></component><button @click="switchComponent">切换组件</button></div>
</template><script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';export default {data() {return {currentComponent: ComponentA,currentRef: 'componentRef',componentRef: null};},methods: {switchComponent() {this.currentComponent = this.currentComponent === ComponentA ? ComponentB : ComponentA;// 切换组件后,确保 $refs 里有正确的组件实例if (this.$refs.componentRef) {this.$refs.componentRef.someMethod();}}}
};
</script>

5. 在子组件销毁时清理 $refs

当子组件被销毁的时候,$refs 里对应的引用不会自动清除。所以,要是你在子组件销毁后还去访问 $refs 里的这个引用,就会报错。为了避免这种情况,你可以在子组件销毁的时候手动清理 $refs 里的引用。

<template><div><child-component ref="childRef"></child-component><button @click="destroyChild">销毁子组件</button></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},methods: {destroyChild() {// 销毁子组件this.$refs.childRef.$destroy();// 手动清理 $refs 里的引用this.$refs.childRef = null;}}
};
</script>

总之,$refs 是个很强大的工具,但使用的时候得注意上面这些点,这样才能避免出现各种奇怪的问题,让你的 Vue 项目更加稳定。

除了$refs,Vue还有哪些可以访问组件实例或DOM元素的方式?

在 Vue 里,除了使用 $refs 访问组件实例或 DOM 元素外,还有以下几种方式:

1. 通过事件机制传递信息

在 Vue 中,你可以利用自定义事件和事件总线在组件间传递数据,从而间接访问组件实例。

自定义事件

子组件能够通过 $emit 触发自定义事件,把数据传递给父组件,父组件在接收到事件后就可以访问子组件实例的属性或方法。

<template><!-- 父组件 --><div><child-component @custom-event="handleCustomEvent"></child-component></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},methods: {handleCustomEvent(childInstance) {// 访问子组件实例console.log(childInstance.someMethod());}}
};
</script>
<template><!-- 子组件 --><div><button @click="sendInstance">发送实例</button></div>
</template><script>
export default {methods: {sendInstance() {// 触发自定义事件,传递当前组件实例this.$emit('custom-event', this);},someMethod() {return '这是子组件的方法';}}
};
</script>
事件总线

事件总线是一个全局的事件中心,组件能够在上面触发和监听事件,以此实现组件间的通信。

// eventBus.js
import Vue from 'vue';
export const eventBus = new Vue();
<template><!-- 发送组件 --><div><button @click="sendMessage">发送消息</button></div>
</template><script>
import { eventBus } from './eventBus.js';export default {methods: {sendMessage() {// 触发事件总线的事件eventBus.$emit('message-sent', this);}}
};
</script>
<template><!-- 接收组件 --><div></div>
</template><script>
import { eventBus } from './eventBus.js';export default {mounted() {// 监听事件总线的事件eventBus.$on('message-sent', (senderInstance) => {console.log(senderInstance.someMethod());});}
};
</script>

2. 使用 provideinject

provideinject 主要用于实现跨级组件间的通信,父组件能够通过 provide 提供数据,子组件可以使用 inject 注入这些数据。

<template><!-- 父组件 --><div><child-component></child-component></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},provide() {return {parentInstance: this};}
};
</script>
<template><!-- 子组件 --><div></div>
</template><script>
export default {inject: ['parentInstance'],mounted() {// 访问父组件实例console.log(this.parentInstance.someMethod());}
};
</script>

3. 使用 Vue.observable(Vue 2)或 reactive(Vue 3)

在 Vue 2 里可以使用 Vue.observable 创建一个响应式对象,在 Vue 3 中则使用 reactive。通过这个响应式对象存储组件实例,从而实现对组件实例的访问。

Vue 2
// store.js
import Vue from 'vue';export const store = Vue.observable({componentInstance: null
});
<template><!-- 组件 A --><div><button @click="setInstance">设置实例</button></div>
</template><script>
import { store } from './store.js';export default {methods: {setInstance() {// 将当前组件实例存储到响应式对象中store.componentInstance = this;}}
};
</script>
<template><!-- 组件 B --><div></div>
</template><script>
import { store } from './store.js';export default {mounted() {// 访问存储的组件实例if (store.componentInstance) {console.log(store.componentInstance.someMethod());}}
};
</script>
Vue 3
// store.js
import { reactive } from 'vue';export const store = reactive({componentInstance: null
});
<template><!-- 组件 A --><div><button @click="setInstance">设置实例</button></div>
</template><script setup>
import { store } from './store.js';const setInstance = () => {// 将当前组件实例存储到响应式对象中store.componentInstance = getCurrentInstance();
};
</script>
<template><!-- 组件 B --><div></div>
</template><script setup>
import { store } from './store.js';if (store.componentInstance) {console.log(store.componentInstance.someMethod());
}
</script>

这些方法都有各自的适用场景,你可以根据具体需求来选择合适的方式。

在Vue中,如何避免$refs访问带来的性能问题?

在 Vue 里使用 $refs 访问组件实例或 DOM 元素时,若使用不当可能会引发性能问题。以下是一些避免 $refs 访问带来性能问题的方法:

1. 避免在渲染循环中频繁访问 $refs

$refs 本身并非响应式的,但在渲染循环里频繁访问 $refs 会导致不必要的计算和 DOM 操作,从而降低性能。应该把 $refs 的访问逻辑移到事件处理函数或者生命周期钩子函数中。

<template><div><div ref="myElement">示例元素</div><button @click="handleClick">点击</button></div>
</template><script>
export default {methods: {handleClick() {// 在事件处理函数中访问 $refsconst element = this.$refs.myElement;if (element) {// 对元素进行操作element.style.color = 'red';}}}
};
</script>

2. 仅在必要时使用 $refs

$refs 主要用于直接访问组件实例或 DOM 元素,不过很多时候可以借助 Vue 的响应式系统来实现相同的功能,从而避免使用 $refs

示例:动态改变样式

不使用 $refs 的情况:

<template><div><div :style="{ color: textColor }">示例元素</div><button @click="changeColor">改变颜色</button></div>
</template><script>
export default {data() {return {textColor: 'black'};},methods: {changeColor() {this.textColor = 'red';}}
};
</script>

3. 及时清理不再使用的 $refs

当组件被销毁时,$refs 里对应的引用不会自动清除。若不清理,可能会造成内存泄漏。所以在组件销毁时要手动清理 $refs

<template><div><child-component ref="childRef"></child-component><button @click="destroyChild">销毁子组件</button></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},methods: {destroyChild() {// 销毁子组件this.$refs.childRef.$destroy();// 手动清理 $refs 里的引用this.$refs.childRef = null;}}
};
</script>

4. 避免在 watch 中频繁访问 $refs

watch 用于监听数据变化,若在 watch 里频繁访问 $refs,会导致不必要的性能开销。可以在 watch 中设置 immediate: false,避免初始化时就执行访问操作。

<template><div><div ref="myElement">示例元素</div><input v-model="inputValue" /></div>
</template><script>
export default {data() {return {inputValue: ''};},watch: {inputValue: {handler(newValue) {if (this.$refs.myElement) {// 对元素进行操作this.$refs.myElement.textContent = newValue;}},immediate: false // 避免初始化时执行}}
};
</script>

5. 利用缓存机制

要是需要多次访问 $refs,可以把访问结果缓存起来,避免重复访问。

<template><div><div ref="myElement">示例元素</div><button @click="doSomething">执行操作</button><button @click="doAnotherThing">执行另一个操作</button></div>
</template><script>
export default {data() {return {cachedElement: null};},methods: {getElement() {if (!this.cachedElement) {this.cachedElement = this.$refs.myElement;}return this.cachedElement;},doSomething() {const element = this.getElement();if (element) {// 对元素进行操作element.style.fontSize = '20px';}},doAnotherThing() {const element = this.getElement();if (element) {// 对元素进行另一个操作element.style.backgroundColor = 'yellow';}}}
};
</script>

通过以上这些方法,可以有效避免 $refs 访问带来的性能问题,提升 Vue 应用的性能和稳定性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/899349.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【安全运营】关于攻击面管理相关概念的梳理(二)

CYNC&#xff08;持续可见性和网络控制&#xff09; CYNC&#xff08;Continuous Visibility and Network Control&#xff09;即“持续可见性和网络控制”&#xff0c;是一个与网络安全和IT运营管理相关的概念。它强调的是在一个组织的数字环境中&#xff0c;确保对所有资产、…

【区块链安全 | 第二篇】区块链概念详解

文章目录 概述1. 区块链类型2 区块链五层架构3 账本模型4. 节点&#xff08;Node&#xff09;5. 区块&#xff08;Block&#xff09;6. 区块链&#xff08;Blockchain&#xff09;7. 区块链工作流程 核心技术1. 共识机制2. 智能合约 主要组件1. 交易&#xff08;Transaction&am…

Redisson - 分布式锁和同步器

文章目录 锁&#xff08;Lock&#xff09;公平锁&#xff08;Fair Lock&#xff09;联锁&#xff08;MultiLock&#xff09;红锁&#xff08;RedLock&#xff09; 【已废弃】读写锁&#xff08;ReadWriteLock&#xff09;信号量&#xff08;Semaphore&#xff09;可过期许可信号…

HarmonyOS:GridObjectSortComponent(两个Grid之间网格元素交换)

一、概述 网格对象的编辑排序是用于网格对象的编辑、拖动排序、新增和删除。 说明 该组件从API Version 11开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 二、导入模块 import { GridObjectSortComponent, GridObjectSortComponentItem…

RFID技术在机器人中的核心应用场景及技术实现

一、机器人定位与导航 1. 地标定位系统 实现方式: 在环境关键点部署无源RFID标签(如UHF Tag),机器人携带读写器通过读取标签ID实现绝对定位# 伪代码:RFID地标定位 def get_robot_position():detected_tags = reader.read_tags()known_positions = {tag1: (x1,y1), tag2: …

uv 命令用conda命令解释

uv&#xff1a;安装 | uv-zh-cn 功能 | uv-zh-cn #showkey -a 可看按键的"\eOP"转义序列是啥# 绑定快捷键 f1 到 source .venv/bin/activate函数 bind "\eOP": "source .venv/bin/activate " #conda activate# 绑定快捷键 f2 到uv add函数 …

《探秘SQL的BETWEEN:解锁数据范围查询的深度奥秘》

在数据的广袤宇宙中&#xff0c;结构化查询语言&#xff08;SQL&#xff09;宛如一座精密的导航系统&#xff0c;引导我们穿越数据的浩瀚星河&#xff0c;精准定位所需信息。其中&#xff0c;BETWEEN作为SQL的关键工具之一&#xff0c;以其独特的能力&#xff0c;在数据的海洋里…

大型语言模型的秘密:思考链长度与提示格式的魔力

嘿&#xff0c;朋友们&#xff01;今天我要和大家聊聊一个超级酷的话题——大型语言模型&#xff08;LLMs&#xff09; 它们在“思考”和回答问题时的一些“小秘密”。你可能已经听说过**“思考链”&#xff08;Chain of Thought, COT** 这个概念&#xff0c;它是一种让模型在回…

RHCE工程师特训指南

RHCE&#xff08;红帽认证工程师&#xff09;是Linux领域极具含金量的认证之一&#xff0c;其考试以实操为主&#xff0c;注重系统管理、网络服务配置及自动化运维能力。以下内容可帮助对RHCE考生高效规划学习路径。 一、RHCE认证概述 认证结构 RHCE认证分为两部分&#xff…

Vue 3 中 slot插槽的使用方法

插槽&#xff0c;名字挺新奇。但不要被他的名字难住。其实就是父组件向子件件传递信息的一种手段。我们可以用这样的方法向子组件传值。 父组件&#xff08;app.vue) <template><MyCompoent :transData"{a:reactiveObj.a,breactiveObj.b,c}"> </tem…

大模型中的召回次数是什么意思

大模型中的召回次数是什么意思 在大语言模型&#xff08;LLM&#xff09;和检索增强生成&#xff08;RAG&#xff09;系统中&#xff0c;召回次数&#xff08;Recall Count&#xff09;是一个重要的参数&#xff0c;它决定了在检索阶段从知识库中提取多少候选文档或片段。这个…

智能监控视频聚合平台,GB28181/RTSP/SIP/RTMP直播会议融合方案

全场景智能监控聚合平台&#xff1a;打破边界&#xff0c;赋能高效协同 在数字化转型加速的今天&#xff0c;海量视频监控设备、多样化的编码协议与复杂的业务场景&#xff0c;让企业面临跨系统整合难、资源调度效率低、协作响应慢等痛点。我们的智能监控聚合平台以技术创新为…

IP数据报报文格式

一 概述 IP数据报由两部分组成&#xff1a;首部数据部分。首部的前一部分是固定长度&#xff0c;一共20字节大小&#xff0c;是所有IP数据报文必须具有的&#xff1b;固定部分后面是一些可选字段&#xff0c;其长度是可变的。 二 首部固定部分各字段意义 &#xff08;1&…

【电子通识】案例:为什么电子产品制造过程中使用马克笔在FFC/FPC连接器打点进行标记

在电子产品制造过程中&#xff0c;使用马克笔在FFC/FPC连接完成后进行打点标记&#xff08;或类似目视化检查方法&#xff09;&#xff0c;是一种常见的“过程防错&#xff08;Poka-Yoke&#xff09;”手段&#xff0c;其核心目的是通过简单、直观的方式确保关键工序的执行质量…

Electron应用生命周期全解析:从启动到退出的精准掌控

一、Electron生命周期的核心特征 1.1 双进程架构的生命周期差异 Electron应用的生命周期管理具有明显的双进程特征&#xff1a; 主进程生命周期&#xff1a;贯穿应用启动到退出的完整周期渲染进程生命周期&#xff1a;与浏览器标签页相似但具备扩展能力进程间联动周期&#…

Oracle到MySQL实时数据互通:透明网关跨库查询终极方案

技术架构概述 节点类型IP示例Oracle数据库172.18.0.11透明网关节点192.168.5.20MySQL数据库10.10.8.100 提示&#xff1a;透明网关支持部署在Oracle服务器实现集中式管理 一、MySQL环境准备 1. ODBC驱动部署 从MySQL官网获取对应版本的ODBC驱动&#xff1a; # 企业版推荐使…

Linux中断处理流程

Linux中断处理流程 在Linux内核中&#xff0c;中断控制器管理硬件中断号到Linux中断号的映射&#xff0c;并通过中断描述符&#xff08;struct irq_desc&#xff09;进行管理。存储这种映射关系的方式取决于中断编号的连续性&#xff0c;具体实现如下&#xff1a; 1. 数组存储&…

JVM 如何打破双亲委派模型?

虽然双亲委派模型是 Java 类加载机制的推荐实现方式&#xff0c;但在某些情况下&#xff0c;为了实现特定的功能&#xff0c;可能需要打破双亲委派模型。以下是一些常见的打破双亲委派模型的方法和场景&#xff1a; 1. 重写 loadClass 方法 (不推荐): 原理&#xff1a; java.l…

Java 大视界 -- 基于 Java 的大数据隐私计算在医疗影像数据共享中的实践探索(158)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…