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>
CodePudding user response:
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>
CodePudding user response:
Maybe like following snippet:
const { ref, onMounted } = Vue
const app = Vue.createApp({
el: "#demo",
setup() {
const text = ref(null)
onMounted(() => {
console.log(text.value)
})
return { text }
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3"></script>
<div id="demo">
<div ref="text">some text</div>
</div>