intlify / vue-i18n

Vue I18n for Vue 3
https://vue-i18n.intlify.dev/
MIT License
2.13k stars 326 forks source link

Exposing methods for Script Setup 'SFC Composition API Syntax Sugar' #138

Open ux-engineer opened 3 years ago

ux-engineer commented 3 years ago

Vue 3 has this yet experimental syntax Script Setup 'SFC Composition API Syntax Sugar'.

I'm wondering how to best expose the translation method t in components written with this syntax.

Currently this syntax is working for me:

<script setup lang="ts">
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

export const name = 'ViewName';

// Note: vue-meta package does not support Vue 3 as of yet, but am verifying functionality
// by being able to use this object in template syntax.
export const metaInfo = {
  title: t('PAGE_TITLE'),
  meta: [
    { name: 'description', content: t('PAGE_DESCRIPTION') },
  ],
};
</script>

<template>
  <h1>{{ metaInfo.title }}</h1>
</template>

However, I would like to be able to write it like this:

<script setup lang="ts">
export const name = 'ViewName';

export const metaInfo = {
  title: $t('PAGE_TITLE'),
  meta: [
    { name: 'description', content: $t('PAGE_DESCRIPTION') },
  ],
};
</script>

Would it be possible for this library to automatically expose $t method in script setup scope? Or by object-destructuring from setup context <script setup="_, { $t }" lang="ts">?

natemate90 commented 3 years ago

The global exposure of the t() would be a great improvement, as I understand it, $t() cannot make use of the typed translation schema?

Liwoj commented 2 years ago

Note that script setup proposal linked in OP was dropped. Current Vue 3 script setup is based on the new proposal which has no setup context

If I understand it correctly, auto exposing composer functions would require tapping into SFC compiler or writing bundler plugin similar to unplugin-auto-import and I'm not convinced the benefits outweigh the complexity of the solution...especially when you can use above mentioned plugin to completely eliminate the import statement (plugin has already vue-i18n preset)

natemate90 commented 2 years ago

@Liwoj So the import of the local composition function t() would be possible globally with unplugin-auto-import?

Liwoj commented 2 years ago

@natemate90 Nope. unplugin-auto-import can only do the import part (import { useI18n } from 'vue-i18n';). You still need to call it - (it's not import) const { t } = useI18n(); to get a t (or d etc)