Home > front end >  use onMounted Hook
use onMounted Hook

Time:03-08

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

CodePudding user response:

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

  • Related