Marnix Elling
Marnix Elling

Reputation: 389

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>

Upvotes: 12

Views: 41551

Answers (1)

kissu
kissu

Reputation: 46696

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>
const myCoolDiv = ref(null)

const clickMe = () => console.log(myCoolDiv)
</script>

<template>
  <button @click="clickMe">show me the ref</button>
  <div ref="myCoolDiv">
    hello there
  </div>
</template>

Upvotes: 13

Related Questions