【问题标题】:use onMounted Hook使用 onMounted Hook
【发布时间】:2022-09-28 18:31:21
【问题描述】:

我正在为我的网站使用 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

    标签: vue.js nuxt.js vuejs3 server-side-rendering nuxtjs3


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2021-07-16
      • 2023-02-03
      • 2022-01-20
      • 1970-01-01
      • 2021-08-02
      • 2011-07-22
      • 2021-12-08
      • 2021-07-15
      相关资源
      最近更新 更多