nuxt 3 中的自定义插件类型未知

问题描述 投票:0回答:1

在我的 nuxt 3 应用程序中,我在plugins/文件夹中创建了一个插件。

// plugins/customPlugin.ts

export default defineNuxtPlugin(() => ({
   provide: {
      hello: (msg: string) => console.log(`This is your message: ${msg}`),
   },
}));

然后我在我的组件中使用它,例如:

// component.vue 

const { $hello } = useNuxtApp();

$hello('custom message');

它有效,在浏览器控制台中我看到了我的日志。 但问题是,打字稿在 IDE 中给了我一个错误,说 $hello 是“TS2571:对象的类型为‘未知’”

尝试删除节点模块和.nuxt文件夹并重新安装它们,但没有成功。

vue.js nuxt.js nuxtjs3
1个回答
0
投票

这个方法对我有用。

~/plugins/<filename>.ts

export default defineNuxtPlugin(() => {
  function hello(name: string) {
    return `Hello ${name}`
  }
  return { provide: { hello } }
})

<script lang="ts" setup>
const { $hello } = useNuxtApp();

const output = $hello('custom message');
</script>

当您将鼠标悬停在

$hello
上时,它将显示正在输入的内容 enter image description here

基于打字插件获得正确打字的另一种方法文档

index.d.ts

declare module '#app' {
  interface NuxtApp {
    $hello(msg: string): string
  }
}
export { }

© www.soinside.com 2019 - 2024. All rights reserved.