Nuxt 3 插件

nuxt3
Created 3/8/2022
Updated 3/20/2023

Nuxt 3 插件

参考

Nuxt Plugin 插件可以对应用的运行时 Runtime nuxtApp 进行扩展

对比

模块系统与插件系统类似,都是为了扩展 Nuxt 的功能,但是插件系统与项目更加耦合,而模块系统则更独立,可以通过 npm 包的方式来发布,这样方便在不同项目之间使用

通过函数 defineNuxtPlugin(fn) 创建一个插件

其中 fn 是一个函数,它接收一个参数 nuxtApp 是 Nuxt 应用运行时上下文 Runtime

ts
export default defineNuxtPlugin(nuxtApp => {
  // Doing something with nuxtApp
})

使用组合式 API

可以在插件中使用组合式 API(包括在项目的 📁 composables 目录中自定义的组合式函数)

ts
export default defineNuxtPlugin((NuxtApp) => {
  const foo = useFoo()
})
注意

不是所有组合式 API 都可以在插件中使用

  • 因为插件是依序载入的,所以无法使用之后才引入的插件中所提供的组合式 API
  • 因为插件只能读取应用的运行时上下文 nuxtApp,所以无法使用 Vue 所提供的关于生命周期的组合式 API(钩子函数),因为它们一般与组件实例相绑定

提供工具函数

如果希望通过插件为 Nuxt 应用提供 helper 工具函数,可以在插件最后返回的对象的属性 provide 中进行设置

plugins/example.ts
ts
export default defineNuxtPlugin(() => {
  return {
    provide: {
      // 提供一个 helper 函数
      hello: (msg: string) => `Hello ${msg}!`
    }
  }
})

然后在其他项目中就可以使用这个工具函数

vue
<template>
  <div>
    {{ $hello('world') }}
  </div>
</template>
<script setup lang="ts">
const { $hello } = useNuxtApp()
</script>

Copyright © 2024 Ben

Theme BlogiNote

Icons from Icônes