DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on

4

Quick hack for using google translate (or other services) in Nuxt/Vue.js

Hey guys, here's a quick way of making google translate play nice using setInterval.

export default {
    mounted: function()
    {
        this.$nextTick(() => {
            this.googleTranslateInit();
        });

    },

    methods: {

        googleTranslateInit: function() {

            let checkIfGoogleLoaded = setInterval(() => {

                if (google.translate.TranslateElement != null) {
                    clearInterval(checkIfGoogleLoaded);

                    this.googleTranslateElement('google_translate_element');
                }

            }, 100);

        },

        googleTranslateElement: function(id) {
            new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, id);
        }

    },
};
Enter fullscreen mode Exit fullscreen mode

It's not always easy to have a nice callback available for google translate, especially if you're nested into a component. I'm only using NUXT's external resources setup for directly loading the library, and ignored creating a plugin for this (although I think that's still valid, to create a script and use an onLoad function

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (3)

Collapse
 
lewiscowles1986 profile image
Lewis Cowles

Surely binding to onMutation event handler, then just initing on the root element is the way to go?

Collapse
 
coolgoose profile image
Alexandru Bucur

hey Lewis, sounds, interesting. How would you do it in that case ? I assume you're talking about MutationObservers right ?

Collapse
 
fezebr profile image
faezeh ebrahimy

hi
i use this code but i have this error in console:
index.vue?6ced:29 Uncaught ReferenceError: google is not defined

google in google.translate.TranslateElement

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay