<template>
<div class="home">
<el-input
style="width: 200px; margin-right: 20px"
v-for="i in data"
:key="i.label"
:ref="inputRef"
v-model="i.value"
></el-input>
<el-button @click="add">...</el-button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref, Ref, nextTick } from "vue";
export default defineComponent({
name: "Home",
setup() {
const state = reactive({
data: [
{ label: "小朋友1", value: "" },
{ label: "小朋友2", value: "" },
{ label: "小朋友3", value: "" },
{ label: "小朋友4", value: "" },
],
});
const arr: Ref<any> = ref([]);
function inputRef(el: HTMLElement) {
// 断言为HTMLElement类型的数组
(arr.value as Array<HTMLElement>).push(el); // 此处add 会重复添加DOM
}
function add() {
state.data.push({ label: "", value: "" });
arr.value = []; // 重点 每次添加前 清空DOM
nextTick(() => {
arr.value[state.data.length - 1].input.focus();
});
}
return {
...toRefs(state),
inputRef,
add,
};
},
});
</script>
<style lang='scss' scoped>
.home {
height: 100%;
}
</style>