• Vue3 动态设置 ref


    介绍

    在一些场景,ref设置是未知的需要根据动态数据来决定,如表格中的input框需要我们主动聚焦,就需要给每一个input设置一个ref,进而进行聚焦操作。

    Demo

    点击下面截图中的编辑按钮,自动聚焦到相应的输入框中。
    在这里插入图片描述

    <template>
      <!-- 动态ref -->
      <div class="test_ref">
        <div v-for="item in 9" :key="item">
          <span>{{ item }}</span>
    
          <!-- 动态设置ref -->
          <el-input
            v-model="inputVal"
            placeholder="Please input"
            :ref="(el:refItem) => handleSetInputMap(el, item)"
          />
    
          <el-button type="primary" :icon="Edit" @click="handleEdit(item)" />
        </div>
      </div>
    </template>
    
    <script lang="ts" setup>
    import { ref } from "vue";
    import { Edit } from "@element-plus/icons-vue";
    import { ComponentPublicInstance } from "vue";
    type refItem = Element | ComponentPublicInstance | null;
    const inputVal = ref();
    const inputRefMap = ref({});
    
    /** 编辑 */
    const handleEdit = (item: number) => {
      // 若输入框此时还没有渲染出来,如先隐藏再触发显示 需要使用nextTick进行聚焦
      inputRefMap.value[`Input_Ref_${item}`].input.focus();
    };
    
    /** 动态设置Input Ref */
    const handleSetInputMap = (el: refItem, item: number) => {
      if (el) {
        inputRefMap.value[`Input_Ref_${item}`] = el;
      }
    };
    </script>
    
    <style lang="scss" scoped>
    .test_ref {
      padding: 50px;
      > div {
        width: 300px;
        margin: 0 auto;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 20px;
        margin-bottom: 10px;
      }
    }
    </style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    效果

    在这里插入图片描述

  • 相关阅读:
    车载软件架构 —— 持续集成持续交付
    【Redis】Redis Cluster-集群故障转移
    超级计算机技术学习与研究
    Vim文档编辑器常用语法总结
    ARM开发(一)预备知识——半导体器件,模拟数字部分,计算机组成及原理
    ES6 Reflect
    第G8周:ACGAN任务
    【Java八股文总结】之Java基础
    随记 | 我的 CSDN 两周年创作纪念日
    Jenkins修改端口和工作目录
  • 原文地址:https://blog.csdn.net/qq_36330228/article/details/134466234