Vue 3中的ref和template refs详解(含Vue2迁移到Vue3方法)
Vue 3中的ref和template refs详解在Vue 3中,ref和模板引用(template refs)是两个相关但不同的概念,它们在组合式API(Composition API)中扮演着重要角色。
ref - 响应式引用
ref是Vue 3中创建响应式数据的主要方式之一。
基本用法
import { ref } from 'vue'
// 创建一个响应式引用
const count = ref(0)
// 访问或修改值需要使用.value
console.log(count.value) // 0
count.value++
console.log(count.value) // 1特点
[*]包装原始值:ref可以将基本类型(如数字、字符串、布尔值)转换为响应式对象
[*]需要使用.value:在JavaScript中访问或修改ref值时,必须使用.value属性
[*]在模板中自动解包:在模板中使用时,Vue会自动解包ref,不需要写.value
<template>
{{ count }}
</template>复杂数据结构
对于对象和数组,ref内部使用reactive来实现响应式:
const user = ref({
name: '张三',
age: 30
})
// 修改属性
user.value.age = 31template refs - 模板引用
模板引用允许你直接访问DOM元素或组件实例。
Vue 2中的使用方式
在Vue 2中,我们通过this.$refs访问模板引用:
<template>
<input ref="inputElement">
<ChildComponent ref="childComponent"/>
</template>Vue 3中的使用方式
在Vue 3的组合式API中,模板引用的使用方式发生了变化:
[*]创建ref变量:首先创建一个ref变量
[*]在模板中绑定:将这个ref变量绑定到元素或组件上
[*]在组件挂载后访问:组件挂载后,ref变量的.value将包含对应的DOM元素或组件实例
<template>
<input ref="inputElement">
<ChildComponent ref="childComponent"/>
</template>动态模板引用(v-for中使用)
在循环中使用模板引用时,需要使用函数形式的ref:
<template>
<ul>
<li v-for="(item, i) in list" :key="i" :ref="el => { if (el) itemRefs = el }">
{{ item }}
</li>
</ul>
</template>示例:关于v-for生成的ref的复杂例子,Vue2+js移植到Vue3+TS
旧的Vue2+js程序:
<template>
<input ref="inputElement">
<ChildComponent ref="childComponent"/>
</template><template>
<input ref="inputElement">
<ChildComponent ref="childComponent"/>
</template>// 使用到ref的位置示例,type获取细节不表
const refMap = {
'in-gain': `col-${channel}`,
'out-gain': `row-${channel}`,
'node-gain': `row-${channel}-col-${nodeInputChannel}`,
'in-btn': `col-${channel}`,
'out-btn': `row-${channel}`,
'node-btn': `row-${channel}-col-${nodeInputChannel}`,
};
const refName = refMap;
if (!refName) {
console.error('Unknown type:', type);
return null;
}
// 处理数组型 ref(v-for 产生的)
const refs = this.$refs;在示例中,需要从Vue 2风格的$refs迁移到Vue 3的模板引用方式。具体步骤:
[*]定义模板引用数组:
const inputGainRefs = ref([])
const outputGainRefs = ref([])
const nodeGainRefsMap = ref([])
[*]在模板中使用这些引用:
[*]在需要访问子组件时:
// 访问输入增益组件
inputGainRefs.value.someMethod()
// 访问节点增益组件
nodeGainRefsMap.value.someMethod()总结
[*]ref:用于创建响应式数据,在JavaScript中需要使用.value访问
[*]template refs:用于访问DOM元素或组件实例
[*]在Vue 2中通过this.$refs访问
[*]在Vue 3中通过创建ref变量并在模板中绑定来实现
[*]迁移策略:
[*]创建对应的ref变量
[*]在模板中使用:ref绑定
[*]在组件挂载后通过.value访问实际元素或组件
这种方式不仅符合Vue 3的组合式API设计理念,还提供了更好的类型推断支持,特别是在使用TypeScript的项目中。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]