
大家好我是Java1234_小锋老师最近更新 《一天学会 Vue3 Vite element-plus UI框架 视频教程》专辑感谢大家支持。本课程主要介绍和讲解 Vue3框架Vite构建工具以及element-plus UI框架。Vue3核心知识介绍Vite构建工具使用以及element-plus UI框架的基础组件配置组件Form 表单组件Data 数据展示组件Navigation导航组件Feedback反馈组件Container布局组件介绍和使用。视频教程课件源码打包下载 链接https://pan.baidu.com/s/1o-zRfndo1HHrS_uFroOiCw?pwd1234提取码1234具体位置 - 第四阶段富客户端技术里面Vue3专题 - 模板引用 ref模板引用用来拿到页面上某个真实 DOM 元素或子组件实例。声明式数据绑定解决不了时比如聚焦输入框、量尺寸、调第三方库就用它。适合自动聚焦、滚动到某处、读取元素宽高、调用子组件方法等场景。1. 为什么需要模板引用Vue 提倡用数据驱动视图多数时候改ref/reactive就够了。但有些事必须直接碰 DOM// 比如页面加载后让输入框自动获得焦点inputEl.focus()// 比如读取某个盒子的实际宽度boxEl.offsetWidth这时用ref属性把模板里的节点「挂」到脚本变量上。2. 基本用法在模板元素上写ref名字脚本里用同名的ref(null)接收。挂载完成后变量的.value就是对应 DOM。script setup /** * 模板引用基础 Demo * 点击按钮让输入框获得焦点 */ import { ref } from vue // 用来存放 input 的 DOM 引用初始为 null const inputRef ref(null) /** 聚焦输入框 */ function focusInput() { // 挂载后才有值使用前建议判断一下 inputRef.value?.focus() } /script template input refinputRef placeholder点下方按钮聚焦我 / button clickfocusInput聚焦输入框/button /template运行截图要点script setup里模板refinputRef会自动匹配同名的inputRef脚本里访问要用.valueinputRef.value组件挂载前是null操作 DOM 建议放在点击事件、onMounted里3. 入门 Demo自动聚焦页面一打开就聚焦搜索框用onMountedscript setup /** * 自动聚焦 Demo * 组件挂载后自动 focus 输入框 */ import { ref, onMounted } from vue const searchRef ref(null) onMounted(() { // 此时 DOM 已渲染完成可以安全操作 searchRef.value?.focus() }) /script template h3搜索/h3 input refsearchRef placeholder打开页面就会聚焦这里 / /template运行截图4. 入门 Demo读取元素尺寸script setup /** * 读取 DOM 尺寸 Demo * 点击按钮显示盒子的宽高 */ import { ref } from vue const boxRef ref(null) const info ref(尚未测量) /** 读取盒子宽高 */ function measure() { const el boxRef.value if (!el) return info.value 宽${el.offsetWidth}px高${el.offsetHeight}px } /script template div refboxRef stylewidth: 200px; height: 100px; background: #e8f4ff; line-height: 100px; text-align: center; 测量我 /div p{{ info }}/p button clickmeasure测量尺寸/button /template运行截图5. 入门 Demov-for 中的引用列表里多个元素都要引用时用函数式ref把每个 DOM 推进数组script setup /** * v-for 模板引用 Demo * 收集列表每一项的 DOM点击高亮某一项 */ import { ref } from vue const items ref([苹果, 香蕉, 橙子]) const itemRefs ref([]) /** 把每个 li 的 DOM 收集进数组 */ function setItemRef(el) { if (el) { itemRefs.value.push(el) } } /** 高亮第 index 项 */ function highlight(index) { itemRefs.value.forEach((el, i) { el.style.background i index ? #ffe58f : }) } // 注意列表更新前可清空避免重复堆积 // 更稳妥的做法是在更新前itemRefs.value [] /script template ul li v-for(item, index) in items :keyitem :refsetItemRef {{ item }} button clickhighlight(index)高亮/button /li /ul /template说明v-for里不要指望普通字符串ref自动变成数组Composition API 下推荐函数式ref。运行截图