How to switch this.$refs and this.$el in the Vue 3 Composition API

In this article, we find out how to use the new ref() function as a replacement for static and dynamic HTML element references.

The new setup component option is executed before the component is created, once the props are resolved, and serves as the entry point for Composition API’s.

Because the component instance is not yet created when setup is executed, there is no this inside a setup option. This means, with the exception of props, you won’t be able to access any properties declared in the component – local state, computed properties or methods.

When using the Vue 3 Composition API via the setup() method, we don’t have access to this.$refs or this.$el. We can use the new ref() function for the same result.

<template>
  <div ref="el">Hello Vue 3</div>
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const el = ref(null)

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(el.value) // <div>Hello Vue 3</div>
      })

      return {
        el
      }
    }
  }
</script>

Usage with Render Function / JSX

export default {
  setup() {
    const el = ref(null)

    return () =>
      h('div', {
        ref: el
      })

    // with JSX
    return () => <div ref={el} />
  }
}

Usage inside v-for

Composition API template refs do not have special handling when used inside v-for. Instead, use function refs (new feature in 3.0) to perform custom handling:

<template>
  <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
    {{ item }}
  </div>
</template>

<script>
  import { ref, reactive, onBeforeUpdate } from 'vue'

  export default {
    setup() {
      const list = reactive([1, 2, 3])
      const divs = ref([])

      // make sure to reset the refs before each update
      onBeforeUpdate(() => {
        divs.value = []
      })

      return {
        list,
        divs
      }
    }
  }
</script>

#vue 3 #composition api #vue #vuejs #javascript

How to switch this.$refs and this.$el in the Vue 3 Composition API
243.25 GEEK