Nuxt 会自动读取 plugins 目录中的文件并在创建 Vue 应用程序时加载它们;
你可以在文件名中使用 .server 或 .client 后缀来让插件在 服务器端 或 客户端 加载插件
自动注册了哪些文件
只有plugins目录的顶层文件(或任何子目录中的index文件)会被注册为插件。
plugins| - myPlugin.ts // scanned| - myOtherPlugin| --- supportingFile.ts // not scanned| --- componentToRegister.vue // not scanned| --- index.ts // currently scanned but deprecated
只有myPlugin.ts和myOtherPlugin/index.ts会被注册。
创建插件
传递给插件的唯一参数是nuxtApp。
export default defineNuxtPlugin(nuxtApp => {// Doing something with nuxtApp})
在插件中使用 Composables
可以在 Nuxt 插件中使用 Composables
export default defineNuxtPlugin((NuxtApp) => {const foo = useFoo()})
但是,请记住有一些限制和差异:
如果 composable 依赖于后来注册的另一个插件,它可能无法工作。
原因是:插件是依次按顺序调用的,而且是在其他东西之前。这会导致可能会使用一个依赖于另一个尚未被调用的插件的composable。
如果composable依赖于Vue.js的生命周期,它将无法工作。
原因是:通常情况下,Vue.js的composables会绑定到当前的组件实例,而插件只绑定到nuxtApp实例。
自定义插件顺序
插件也是从目录中自动注册的 ,如果需要自定义他们的顺序。
plugins: ['~/plugins/foo.client.js', // only in client side'~/plugins/bar.server.js', // only in server side'~/plugins/baz.js', // both client & server{ src: '~/plugins/both-sides.js' },{ src: '~/plugins/client-only.js', mode: 'client' }, // only on client side{ src: '~/plugins/server-only.js', mode: 'server' } // only on server side]
可以通过在文件名前面加上数字来控制插件的注册顺序
plugins/| - 1.myPlugin.ts| - 2.myOtherPlugin.ts
自动提供帮助方法
如果想在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(),会在这个返回值中发现它们的类型,在模板中也是这样自动处理。 :::info 如果需要在另一个插件中使用提供的 helper,则可以调用useNuxtApp()来获取类型化版本。但一般来说应避免这种情况,除非确定插件的调用顺序。 :::
对于高级用例,可以声明注入属性的类型:
// index.d.tsdeclare module '#app' {interface NuxtApp {$hello (msg: string): string}}declare module '@vue/runtime-core' {interface ComponentCustomProperties {$hello (msg: string): string}}export { }
