Vue3如何動(dòng)態(tài)設(shè)置ref
更新時(shí)間:2024年12月26日 08:56:52 作者:-小龍人
文章介紹了在某些場(chǎng)景下,需要根據(jù)動(dòng)態(tài)數(shù)據(jù)來設(shè)置ref,例如在表格中的輸入框需要聚焦時(shí),需要為每個(gè)輸入框設(shè)置一個(gè)ref,通過點(diǎn)擊編輯按鈕,可以自動(dòng)聚焦到相應(yīng)的輸入框中
Vue3動(dòng)態(tài)設(shè)置ref
介紹
在一些場(chǎng)景,ref設(shè)置是未知的需要根據(jù)動(dòng)態(tài)數(shù)據(jù)來決定,如表格中的input框需要我們主動(dòng)聚焦,就需要給每一個(gè)input設(shè)置一個(gè)ref,進(jìn)而進(jìn)行聚焦操作。
Demo
點(diǎn)擊下面截圖中的編輯按鈕,自動(dòng)聚焦到相應(yīng)的輸入框中。
<template> <!-- 動(dòng)態(tài)ref --> <div class="test_ref"> <div v-for="item in 9" :key="item"> <span>{{ item }}</span> <!-- 動(dòng)態(tài)設(shè)置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) => { // 若輸入框此時(shí)還沒有渲染出來,如先隱藏再觸發(fā)顯示 需要使用nextTick進(jìn)行聚焦 inputRefMap.value[`Input_Ref_${item}`].input.focus(); }; /** 動(dòng)態(tài)設(shè)置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>
效果
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue+axios給開發(fā)環(huán)境和生產(chǎn)環(huán)境配置不同的接口地址
這篇文章主要介紹了詳解vue+axios給開發(fā)環(huán)境和生產(chǎn)環(huán)境配置不同的接口地址,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08如何優(yōu)雅地在vue中添加權(quán)限控制示例詳解
這篇文章主要給大家介紹了關(guān)于如何優(yōu)雅地在vue中添加權(quán)限控制的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03