useTemplateRef使用
1、使用ref方式:
注意ref属性接收的不是一个ref变量,而是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方式
在Vue3.5中新增了一个 useTemplateRef
函数。
useTemplateRef
函数的用法很简单:只接收一个参数 key
,是一个字符串。返回值是一个ref变量。
其中参数key字符串的值应该等于template中ref属性的值。
返回值是一个ref变量,变量的值指向模版引用的DOM元素或者子组件。
<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的应用:动态切换ref绑定的变量
在这个场景template中ref绑定的就是一个变量 refKey
,通过点击 切换ref绑定的变量
按钮可以切换 refKey
的值。相应的,绑定input输入框的变量也会从 inputEl1
变量切换成 inputEl2
变量。
<template>
<input type="text" :value="refKey" />
<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>
posted on 2024-09-26 09:11 springsnow 阅读(630) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构