「如何在Vue3中给元素绑定ref」

·

在Vue2中,元素的ref属性可以通过$ref获取,示例代码:

<template>
  <input ref="inputRef" />
</template>
<script>
...
  mounted:{
    this.$ref['inputRef'].focus()
  }
...
</script>

Vue3的组合式API移除了$ref,写法改为如下:

<template>
  <input ref="inputRef" />
</template>
<script setup>
...
const inputRef = ref(null)
onMounted(() => {
  inputRef.value.focus()
})
...
</script>

v-for中循环绑定ref


<div v-for="item in list" :ref="setItemRef"></div>


<script setup>
...
let itemRefs = []

const setItemRef = (el) => {
  if(el) {
    itemRefs.push(el)
  }
} 
...
</script>

ref绑定到reactive

<template>
  <input :ref="(el) => (inputRefs['input1Ref'] = el)" />

  <input :ref="(el) => (inputRefs.input2Ref = el)" />
</template>

<script setup>
const inputRefs = reactive({
  input1Ref: null,
  input2Ref: null
})

onBeforeUpdate(() => {
  itemRefs = []
})
</script>