<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>
动态 ref 的使用:
:ref 动态地为多个元素绑定 ref。这里我们使用了一个数组 refs 来存储每个输入框的引用。:ref="el => { refs[index] = el }":这行代码为每个输入框动态地分配一个 ref,并将它们存储在 refs 数组中。访问和操作 ref:
refs 是一个响应式的数组,存储了所有输入框的 DOM 引用。focusInput 方法中,我们可以通过 refs.value[1] 访问第二个输入框,并调用其 focus() 方法来聚焦该输入框。按钮点击事件:
focusInput 方法,该方法尝试聚焦第二个输入框(索引为 1)。这样,你就可以通过动态 ref 来方便地管理和操作多个 DOM 元素。
上一篇:vue3 ref调用子组件方法
下一篇:vue3 html
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站