简体   繁体   中英

In vue.js, how can I use i18n in functions.js?

I have created a file with several functions for user, within one of these functions, how can I use i18n? I thought this.$t would work for me, but it doesn't work.

functions.js

import Vue from 'vue'
import moment from 'moment'

export default {

delete() {

        return new Promise((resolve) => {
            Vue.swal({
                title: this.$t('delete'),
                type: 'warning',
                showCancelButton: true,
                //confirmButtonColor: '#3085d6',
                //cancelButtonColor: '#d33',
                confirmButtonText: 'Eliminar',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.value) resolve();
            });
        });
        
    }

{{ $t('back') }} works in <template> and this.$t('back') also works in vue component.

You need to create a file named src/i18n.js with the following content:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locales from "./locales.json";

Vue.use(VueI18n);

const i18n = new VueI18n(
  {
    fallbackLocale: 'en',
    locale: 'en',
    messages: locales,
    silentTranslationWarn: true
  });

export default i18n;

and then import it both in your main.js and functions.js

import i18n from './i18n'
import Vue from 'vue'
import App from './App.vue'

new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app');
import Vue from 'vue'
import moment from 'moment'
import i18n from './i18n'

export default {

delete() {

        return new Promise((resolve) => {
            Vue.swal({
                title: i18n.t('delete'),
                type: 'warning',
                showCancelButton: true,
                //confirmButtonColor: '#3085d6',
                //cancelButtonColor: '#d33',
                confirmButtonText: 'Eliminar',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.value) resolve();
            });
        });
        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM