05编写全球化的插件

在上一章我们使用Pinia实现了全球化。但是在一个应用中不可能只有一个组件,我们需要在每个组件添加重复的计算属性代码,这样很麻烦。而Vue为我们提供了全局扩展属性,这样我们就可以在创建插件时定义扩展属性,在组件中就可以直接使用了。

新增插件文件Plugins/localizationPlugin.ts,添加以下代码完成插件的编写

import { App } from 'vue'
import { useApplicationConfigurationStore } from '@/stores/ApplicationConfiguration'

const localizationPlugin = {
  install (app: App<Element>) {
    // 安装全局可用的属性 国际化方法
    app.config.globalProperties.$l = (key: string) => {
      const store = useApplicationConfigurationStore()
      return store.l(key)
    }
  }
}

export default localizationPlugin

// 在Vue中定义扩展全局属性
export {} // 注意:没有这行代码将覆盖原始类型
declare module 'vue' {
  export interface ComponentCustomProperties {
    /**
     * 国际化语言转换
     * @param key 国际化配置的Key
     * @returns 国际化配置的译文
     */
    $l: (key: string) => string
  }
}

main.ts中安装插件

import localizationPlugin from '@/Plugins/localizationPlugin'
  .use(localizationPlugin)

AboutView.vue控件中就可以直接使用$l了,完整代码:

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <LanguageSelectVue></LanguageSelectVue>
    <div>
      <!-- 直接使用 $l 支持ts的类型推断 -->
      {{ $l('LongWelcomeMessage') }}
    </div>
  </div>
</template>

<script lang="ts">

import { IConfig } from '@/api-client/clientBase'
import { defineComponent } from 'vue'
import { TestClient } from '../api-client/client'
import LanguageSelectVue from '@/components/selects/LanguageSelect.vue'

export default defineComponent({
  components: {
    LanguageSelectVue
  },
  data () {
    return {
        //
    }
  },
  beforeMount () {
    //
  },
  mounted () {
    //
  },
  computed: {
  },
  methods: {
    //
  }
})

</script>
posted @ 2023-01-02 17:00  $("#阿飞")  阅读(55)  评论(0编辑  收藏  举报