vue3【详解】插件 Plugins(含插件的使用场景、编写插件,插件中的 Provide / Inject )

用于为 Vue 添加全局功能

插件是什么?

插件可以是一个拥有 install() 方法的对象,也可以直接是一个安装函数本身。安装函数会接收到安装它的应用实例和传递给 app.use() 的额外选项作为参数:

const myPlugin = {
  install(app, options) {
    // 配置此应用
  }
}

使用场景

  • 通过 app.component() 和 app.directive() 注册一到多个全局组件或自定义指令。

  • 通过 app.provide() 使一个资源可被注入进整个应用。

  • 向 app.config.globalProperties 中添加一些全局实例属性或方法

  • 可能上述三种都包含了的功能库 (例如 vue-router)。

编写插件

i18n国际化插件 为例

1. 定义插件

// plugins/i18n.js
export default {
  install: (app, options) => {
    // 注入一个全局可用的 $translate() 方法
    app.config.globalProperties.$translate = (key) => {
      // 获取 `options` 对象的深层属性
      // 使用 `key` 作为索引
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }
  }
}

2. 安装插件

import i18nPlugin from './plugins/i18n'

app.use(i18nPlugin, {
  greetings: {
    hello: 'Bonjour!'
  }
})

3. 使用插件

<h1>{{ $translate('greetings.hello') }}</h1>

最终页面渲染

Bonjour!

原理
$translate 函数接收一个字符串 greetings.hello ,在翻译字典中查找,并返回翻译得到的值。

插件中的 Provide / Inject

可以将插件接收到的 options 参数提供给整个应用,让任何组件都能使用这个翻译字典对象。

// plugins/i18n.js
export default {
  install: (app, options) => {
    app.provide('i18n', options)
  }
}

在组件中以 i18n 为 key 注入并访问插件的选项对象

<script setup>
import { inject } from 'vue'

const i18n = inject('i18n')

console.log(i18n.greetings.hello)
</script>

相关推荐

  1. vue3 编写

    2024-07-21 09:04:03       29 阅读
  2. 使用vue3编写一个

    2024-07-21 09:04:03       37 阅读
  3. vue3

    2024-07-21 09:04:03       27 阅读
  4. :qrcode使用

    2024-07-21 09:04:03       26 阅读
  5. :vite-plugin-electron

    2024-07-21 09:04:03       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 09:04:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 09:04:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 09:04:03       45 阅读
  4. Python语言-面向对象

    2024-07-21 09:04:03       55 阅读

热门阅读

  1. C++知识点总结(49):树的存储与遍历

    2024-07-21 09:04:03       18 阅读
  2. 内存管理(知识点)

    2024-07-21 09:04:03       19 阅读
  3. 1604 - 高精度除单精度

    2024-07-21 09:04:03       15 阅读
  4. 数据结构(功能受限的表-栈&队列)

    2024-07-21 09:04:03       18 阅读
  5. Linux 下部署 syncthing 中继服务器

    2024-07-21 09:04:03       22 阅读
  6. 云计算遭遇的主要安全威胁

    2024-07-21 09:04:03       15 阅读
  7. 服务发现的艺术:Eureka中实现分布式服务目录

    2024-07-21 09:04:03       18 阅读
  8. 终端创建py虚拟环境

    2024-07-21 09:04:03       16 阅读
  9. log4j2启动异步日志与动态修改日志级别

    2024-07-21 09:04:03       17 阅读
  10. Leetcode【拥有最多糖果的孩子】

    2024-07-21 09:04:03       20 阅读