Vue 3 中 ref
与 nextTick
使用整理
ref
的两种使用方式
1. ref()
用于创建响应式数据
csharp
jsCopyEditimport { ref } from 'vue'
const count = ref(0)
count.value++ // 注意使用 .value
2. ref="xxx"
用于获取 DOM 或组件实例引用
xml
vueCopyEdit<template>
<input ref="inputRef" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
const inputRef = ref(null)
onMounted(() => {
inputRef.value.focus() // 获取 DOM 节点并调用方法
})
</script>
ref="inputRef"
绑定到 DOM 或子组件,配合<script setup>
中的ref(null)
一起使用。
组合式 API 中访问子组件的方法
使用 ref + defineExpose
子组件
xml
vueCopyEdit<script setup>
const sayHello = () => console.log("Hello")
defineExpose({ sayHello })
</script>
父组件
xml
vueCopyEdit<Child ref="childRef" />
<button @click="childRef?.sayHello()">调用子组件</button>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const childRef = ref(null)
</script>
nextTick()
的作用和使用
作用:
等待 DOM 更新完成后 再执行某段逻辑。
常用场景:
- 等待
v-if
切换 DOM 后获取或操作 DOM - 等待响应式数据更新完成后做副作用
- 设置
input.focus()
等
使用方式
javascript
import { nextTick } from 'vue'
nextTick(() => {
// 此处 DOM 已更新
console.log('DOM updated')
})
或:
csharp
const edit = async () => {
isShow.value = false
await nextTick()
inputRef.value?.focus()
}
🧪 示例:点击按钮显示输入框并自动聚焦
xml
vueCopyEdit<template>
<div v-if="isShow">
{{ msg }}
<button @click="edit">编辑</button>
</div>
<div v-else>
<input ref="inputRef" />
<button @click="end">完成</button>
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
const isShow = ref(true)
const msg = ref("hello")
const inputRef = ref(null)
const edit = async () => {
isShow.value = false
await nextTick()
inputRef.value?.focus()
}
const end = () => {
isShow.value = true
}
</script>
总结:
ref="xxx"
用于获取 DOM/组件,nextTick()
用于等待 DOM 更新后执行操作。