Vue插件

浮生半日闲 发布于 2023-09-30 24 次阅读


插件是一种能为Vue提供全局功能的工具代码。

定义

import type { App } from "vue";

export default {
    /**
     * 定义插件
     * @param app   vue对象 
     * @param options  使用插件时,传递的参数
     */
    install: (app: App, options: any) => {
        app.config.globalProperties.$translate = (key: string) => {
            // 处理逻辑
            return 'do something'
        }

        // 注入依赖
        app.provide('i18n', options)
    }
}

引用

// main.ts
import i18n from './plugins/i18n'

const app = createApp(App)
app.use(i18n, {});

使用

// 任意页面中
<template>
    {{ $translate('hello') }}
</template>

<script setup lang="ts">
import { inject } from 'vue'

const i18n = inject('i18n')
</script>