1、使用ref方式:
<template>
<div>
<input type="text" ref="inputEl" />
<button @click="setInputValue">给input赋值</button>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
const inputEl = ref<HTMLInputElement>();
function setInputValue() {
if (inputEl.value) {
inputEl.value.value = "Hello, world!";
}
}
</script>
2、使用useTemplateRef方式
<template>
<input type="text" ref="inputRef" />
<button @click="setInputValue">给input赋值</button>
</template>
<script setup lang="ts">
import { useTemplateRef } from "vue";
const inputEl = useTemplateRef<HTMLInputElement>("inputRef");
function setInputValue() {
if (inputEl.value) {
inputEl.value.value = "Hello, world!";
}
}
</script>
3、使用useTemplateRef的应用
<template>
<input type="text" ref="inputEl1" />
<input type="text" ref="inputEl2" />
<button @click="switchRef">切换ref绑定的变量</button>
<button @click="setInputValue">给input赋值</button>
</template>
<script setup lang="ts">
import { useTemplateRef, ref } from "vue";
const refKey = ref("inputEl1");
const inputEl1 = useTemplateRef<HTMLInputElement>("inputEl1");
const inputEl2 = useTemplateRef<HTMLInputElement>("inputEl2");
function switchRef() {
refKey.value = refKey.value === "inputEl1" ? "inputEl2" : "inputEl1";
}
function setInputValue() {
const curEl = refKey.value === "inputEl1" ? inputEl1 : inputEl2;
if (curEl.value) {
curEl.value.value = "Hello, world!";
}
}
</script>
标签:const,useTemplateRef,value,使用,inputEl,inputEl1,ref
From: https://www.cnblogs.com/springsnow/p/18432714