Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use onMounted Hook

I'm using nuxt3 with vue3 for my website. But I have problem when using onMounted hook.

here is my vue page.

<script setup lang="ts">
  import { onMounted } from '@vue/runtime-core';

  onMounted(() => {
    console.log('myheader mounted');
  })
</script>

<template>
    <h1>test</h1>
</template>

I get this errors:

[Vue warn]: onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

It makes me confused...... T.T

like image 356
KaMui Avatar asked Jun 10 '26 19:06

KaMui


1 Answers

Nuxt requires importing the hooks from vue, not @vue/runtime-core:

<script setup lang="ts">
  // import { onMounted } from '@vue/runtime-core'; ❌
  import { onMounted } from 'vue'; ✅

  onMounted(() => {
    console.log('myheader mounted');
  })
</script>

demo 1

Or use auto imports instead. That is, omit the import, and let Nuxt automatically import onMounted from the correct package:

<script setup lang="ts">
  // onMounted auto imported ✅

  onMounted(() => {
    console.log('myheader mounted');
  })
</script>

demo 2

like image 53
tony19 Avatar answered Jun 13 '26 19:06

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!