使用 onMounted Hook

我在我的网站上使用 nuxt3 和 vue3。但是我在使用 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

stack overflow use onMounted Hook
原文答案
author avatar

接受的答案

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


答案: