在我的 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文件夹并重新安装它们,但没有成功。
这个方法对我有用。
~/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
上时,它将显示正在输入的内容
或
基于打字插件获得正确打字的另一种方法文档
index.d.ts
declare module '#app' {
interface NuxtApp {
$hello(msg: string): string
}
}
export { }