使用 onMounted 钩子

use onMounted Hook

我在我的网站上使用带有 vue3 的 nuxt3。 但是我在使用 onMounted 钩子时遇到问题。

这是我的 vue 页面。

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

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

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

我收到以下错误:

[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.

搞得我一头雾水……T.T

Nuxt 需要 importing the hooks from vue,而不是 @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

或改用auto imports。即省略import,让Nuxt自动从正确的包中导入onMounted

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

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

demo 2