vue.jsnuxt.jsvuejs3nuxt3.js

How to use template refs in Nuxt 3


In Nuxt2 there were template $refs that you could access in <script> with this.$refs

I would like to know what is the Nuxt3 equivalent of this is.

I need this to access the innerText of an element. I am not allowed to use querySelector or getElementById etc.

This is the way we write code. I can give html elements ref="fooBar" but I can't access it with this.$refs.fooBar or even this.$refs.

<script setup lang="ts">
import { ref, computed } from 'vue';

const foo = ref('bar');

function fooBar() {
  //Do stuff
}
</script>

<template>
  //Html here
</template>

Solution

  • With Options API

    <script>
    export default {
      mounted() {
        console.log('input', this.$refs['my-cool-div'])
      }
    }
    </script>
    
    <template>
      <div ref="my-cool-div">
        hello there
      </div>
    </template>
    

    With Composition API

    <script setup>
    import { useTemplateRef } from 'vue'
    
    const myEl = useTemplateRef('myCoolDiv')
    
    const clickMe = () => console.log(myEl)
    </script>
    
    <template>
      <button @click="clickMe">show me the ref</button>
      <div ref="myCoolDiv">
        hello there
      </div>
    </template>