Skip to content

Plugins - 插件目录

Nuxt 会自动读取plugins目录中的文件并加载它们。可以在文件名中使用.server.client后缀(如:focus.client.ts),以便只在服务器或客户端加载一个插件。

所有在plugins目录中的插件都是自动注册的,不必在nuxt.config.ts中单独配置。

哪些文件被注册

只有plugins目录的顶层文件(或任何子目录中的index文件)会被注册为插件。

比如说:

plugins
  | - myPlugin.ts
  | - myOtherPlugin
  | --- supportingFile.ts
  | --- componentToRegister.vue
  | --- index.ts

只有myPlugin.tsmyOtherPlugin/index.ts会被注册。

创建插件

传递给插件的唯一参数是nuxtApp

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

在插件中使用 Composables

可以在 Nuxt 插件中使用Composables

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

但是,请记住有一些限制和差异:

  1. 如果composable依赖于后来注册的另一个插件,它可能无法工作。

原因是:插件是依次按顺序调用的,而且是在其他东西之前。这回导致可能会使用一个依赖于另一个尚未被调用的插件的composable

  1. 如果composable依赖于Vue.js的生命周期,它将无法工作。

原因是:通常情况下,Vue.jscomposables会绑定到当前的组件实例,而插件只绑定到nuxtApp实例。

自动提供帮助方法

如果想在NuxtApp实例上提供helper功能,只需在插件中返回一个带provide键值的对象即可。

例如:

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

在另一个文件中使用:

<template>
  <div>
    <!-- 直接调用 -->
    {{ $hello('world') }}
  </div>
</template>

<script setup lang="ts">
// 也可以在此处使用
const { $hello } = useNuxtApp()
</script>

插件类型

如果从插件返回 helpers,它们将被自动加上类型;如果调用useNuxtApp(),会在这个返回值中发现它们的类型,在模板中也是这样自动处理。

DANGER

如果需要在另一个插件中使用提供的 helper,则可以调用useNuxtApp()来获取类型的版本。但一般来说应避免这种情况,除非确定插件的调用顺序。

进阶

对于高级用例,可以声明注入属性的类型,如下所示:

// index.d.ts

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

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $hello (msg: string): string
  }
}

export { }

Vue 插件

如果想使用 Vue 插件,比如vue-gtag来添加Google Analytics标签,可以使用 Nuxt 插件来实现。

有一个开放的 RFC 使这更容易!参见nuxt/framework#1175

首先,安装你需要的插件:

yarn add --dev vue-gtag-next

然后创建一个插件文件:plugins/vue-gtag.client.js

import VueGtag from 'vue-gtag-next'

export default defineNuxtPlugin((nuxtApp) => {
  // 通过 nuxtApp.vueApp 可以获取 vue 实例
  nuxtApp.vueApp.use(VueGtag, {
    property: {
      id: 'GA_MEASUREMENT_ID'
    }
  })
})

Vue 指令

可以在插件中注册自定义 Vue 指令。例如,在plugins/directive.ts中:

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.directive('focus', {
    mounted (el) {
      el.focus()
    },
    getSSRProps (binding, vnode) {
      // you can provide SSR-specific props here
      return {}
    }
  })
})

Vue 指令文档:https://vuejs.org/guide/reusability/custom-directives.html

Nuxt3插件在线示例:https://v3.nuxtjs.org/examples/app/plugins/