plugins
Nuxt 拥有一个插件系统,用于在创建 Vue 应用时使用 Vue 插件等。
Nuxt 会自动读取 app/plugins/ 目录中的文件,并在创建 Vue 应用时加载它们。
目录内的所有插件都会被自动注册,你无需将它们单独添加到
nuxt.config 中。你可以在文件名中使用
.server 或 .client 后缀,让某个插件只在服务端或客户端加载。已注册的插件
只有目录顶层文件(或任意子目录内的 index 文件)会被自动注册为插件。
Directory structure
-| plugins/
---| foo.ts // 被扫描
---| bar/
-----| baz.ts // 不被扫描
-----| foz.vue // 不被扫描
-----| index.ts // 当前会被扫描,但已废弃
只有 foo.ts 和 bar/index.ts 会被注册。
要添加子目录中的插件,可以使用 nuxt.config.ts 中的 app/plugins 选项:
nuxt.config.ts
export default defineNuxtConfig({
plugins: [
'~/plugins/bar/baz',
'~/plugins/bar/foz',
],
})
创建插件
传给插件的唯一参数是 nuxtApp。
plugins/hello.ts
export default defineNuxtPlugin((nuxtApp) => {
// 对 nuxtApp 做一些操作
})
对象语法插件
也可以使用对象语法定义插件,用于更高级的用例。例如:
plugins/hello.ts
export default defineNuxtPlugin({
name: 'my-plugin',
enforce: 'pre', // 或 'post'
async setup (nuxtApp) {
// 这等价于一个普通的函数式插件
},
hooks: {
// 你可以在这里直接注册 Nuxt 应用的运行时钩子
'app:created' () {
const nuxtApp = useNuxtApp()
// 在钩子中做一些操作
},
},
env: {
// 如果你不希望插件在渲染仅服务端或 island 组件时运行,将此值设为 `false`
islands: true,
},
})