plugins
Nuxt 拥有一个插件系统,可以在创建 Vue 应用程序时使用 Vue 插件和其他功能。
Nuxt 会自动读取 plugins/
目录中的文件,并在创建 Vue 应用程序时加载它们。
插件使用
注册插件
只有在一级目录才会自动注册
只有目录的顶层文件(或任何子目录中的索引文件)才会自动注册为插件
bash
-| plugins/
---| foo.ts // 被扫描
---| bar/
-----| baz.ts // 不被扫描
-----| foz.vue // 不被扫描
-----| index.ts // 目前被扫描,但已弃用
只有foo.ts
和bar/index.ts
会被注册。
要在子目录中添加插件,你可以在 nuxt.config.ts
的 plugins
选项中使用:
js
export default defineNuxtConfig({
plugins: ["~/plugins/bar/baz", "~/plugins/bar/foz"],
});
创建插件
- 方法 通过 nuxtApp 对象
插件只有一个参数,即 nuxtApp。
plugins/hello.ts
js
export default defineNuxtPlugin((nuxtApp) => {
// 使用nuxtApp做一些操作
});
- 对象
js
export default defineNuxtPlugin({
name: "my-plugin",
enforce: "pre", // 或 'post'
async setup(nuxtApp) {
// 这相当于一个普通的功能性插件
},
hooks: {
// 这里可以直接注册Nuxt应用运行时钩子
"app:created"() {
const nuxtApp = useNuxtApp();
//
},
},
env: {
// 如果不希望插件在仅渲染服务器端或孤立组件时运行,请将此值设置为`false`。
islands: true,
},
});
插件执行顺序
可以通过在文件名前面添加“字母”编号来控制插件的注册顺序。
- 目录结构
bash
plugins/
| - 01.myPlugin.ts
| - 02.myOtherPlugin.ts
这样它就会先执行 01 在执行 02