使用useTemplateRef后,模板引用变得更加清晰和直观: 1. 模板中的ref属性值与useTemplateRef的参数保持一致,易于理解和维护。 2.useTemplateRef的返回值是一个标准的ref变量,可以直接访问 DOM 元素或子组件,符合编程直觉。 Hooks 中的 useTemplateRef 在Hooks 中使用useTemplateRef可以避免之前提到的 "隐式依赖" 问题: ...
回到前面讲的hooks的例子,使用useTemplateRef后hooks代码如下: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 exportdefaultfunctionuseInput(key){constinputEl=useTemplateRef<HTMLInputElement>(key);functionsetInputValue(){if(inputEl.value){inputEl.value.value="Hello, world!";}}return{setInputValue,}...
With this new composable, we get type support without needing to manually specify the type of the element. If you want to learn more about template ref, you can check out thedocumentationfor that. Code import{useTemplateRef}from'vue'constinputRef=useTemplateRef('input-ref')onMounted(()=>{inp...
由于在vue组件中我们不需要使用inputEl变量,所以在这里就不需要从useInput中引入变量inputEl了。而之前不使用useTemplateRef的方案中我们就不得不引入inputEl变量了。 动态切换ref绑定的变量 有的时候我们需要根据不同的场景去动态切换ref模版引用的变量,这时在template中ref属性的值就是动态的了,而不是一个写死的字符...
调用useTemplateRef函数时传入的是字符串"inputRef",在useTemplateRef函数内部使用Object.defineProperty方法对refs属性对象进行拦截,拦截的字段为变量key的值,也就是调用useTemplateRef函数传入的字符串"inputRef"。 初始化时,vue处理input输入框上面的ref="inputRef"就会执行下面这样的代码: refs[ref] = value 此时的va...
useTemplateRef 的实现原理 useTemplateRef 的实现并不复杂,本质上 依然是基于 ref 的实现,只不过是在 ref 上进行了封装。 访问vue-next-3.5.0-master/packages/runtime-core/src/helpers/useTemplateRef.ts 下的代码,可以看到 useTemplateRef 的实现逻辑。
useTemplateRef是Vue 3.5中引入的一个Composition API函数,旨在提供一种更清晰、更符合直觉的方式来引用模板中的DOM元素或组件实例。它解决了传统ref属性在模板中使用时的一些混淆和不便,特别是在TypeScript项目中,使得类型推断更加直接和准确。 useTemplateRef的基本使用方法和示例代码 基本使用方法 useTemplateRef函数接收一...
const useRoute: typeof import('vue-router')['useRoute'] const useRouter: typeof import('vue-router')['useRouter'] const useSlots: typeof import('vue')['useSlots'] const useTemplateRef: typeof import('vue')['useTemplateRef'] const watch: typeof import('vue')['watch'] const watchEff...
export function useTemplateRef(key) { // 获取当前 Vue 实例对象。 const i = getCurrentInstance() // 创建一个浅层的ref对象r,初始值为null。 const r = shallowRef(null) //如果存在 Vue 实例 if (i) { // i.refs 默认初始化为 EMPTY_OBJ(空对象)首次使用时动态创建新对象 ...
对于开发者来说Vue3.5版本中还是新增了许多有趣的功能的,比如:onEffectCleanup函数、onWatcherCleanup函数、pause和resume方法、watch的deep选项支持传入数字、useId函数、Teleport组件新增defer延迟属性、useTemplateRef函数。 前言 Vue3.5正式版在这两天发布了,网上已经有了不少关于Vue3.5版本的...