Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue 动态ref

作者:独夜无伴   发布日期:2026-05-01   浏览:101

<template>
  <div>
    <input v-for="(item, index) in items" :key="index" :ref="el => { refs[index] = el }" />
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const items = ref(['item1', 'item2', 'item3']);
    const refs = ref([]);

    const focusInput = () => {
      if (refs.value[1]) {
        refs.value[1].focus();
      }
    };

    return {
      items,
      refs,
      focusInput,
    };
  },
};
</script>

解释说明

  1. 动态 ref 的使用:

    • 在 Vue 3 中,你可以通过 :ref 动态地为多个元素绑定 ref。这里我们使用了一个数组 refs 来存储每个输入框的引用。
    • :ref="el => { refs[index] = el }":这行代码为每个输入框动态地分配一个 ref,并将它们存储在 refs 数组中。
  2. 访问和操作 ref:

    • refs 是一个响应式的数组,存储了所有输入框的 DOM 引用。
    • focusInput 方法中,我们可以通过 refs.value[1] 访问第二个输入框,并调用其 focus() 方法来聚焦该输入框。
  3. 按钮点击事件:

    • 点击按钮时会触发 focusInput 方法,该方法尝试聚焦第二个输入框(索引为 1)。

这样,你就可以通过动态 ref 来方便地管理和操作多个 DOM 元素。

上一篇:vue3 ref调用子组件方法

下一篇:vue3 html

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站