学习链接
vue3 ref 获取单个Dom及多个Dom
示例
- v-if:当flag为true的时候,divRef是有值的;当flag为false的时候,divRef是undefined/null(刚开始是undefined,后面就是null了)
- v-show:divRef都有值
<template>
<div class="main">
Main
<el-button @click="flag = !flag">切换flag - {{ flag }}</el-button>
<el-button @click="logRef">获取divRef</el-button>
<div v-if="flag" ref="divRef">测试divRef</div>
<hr/>
<el-button @click="getFocus">getFocus</el-button>
<el-input ref="iptRef" v-if="iptShow" v-model="iptVal"/>
</div>
</template>
<script setup>
import { ref,reactive, nextTick } from 'vue'
let flag = ref(false)
const divRef = ref()
function logRef () {
console.log(divRef.value);
}
let iptVal =ref('1')
const iptRef = ref()
const iptShow = ref(false)
function getFocus () {
iptShow.value = true
nextTick(() =>{
iptRef.value.focus()
})
}
</script>
<style lang="scss">
</style>