Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do i add Google translate plugin code to my Vue App

Where do I add google translate plugin which has the code of the following type to my Vue App

 <div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'es', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Adding this to template causes error as code or tags which cause side effects are not allowed.

Can I put another script tag in a common component?

like image 563
shivshankar Avatar asked Sep 02 '25 10:09

shivshankar


1 Answers

At least two ways:

  1. Short way: Put it all in public/index.html.

  2. Long way:

Put the scripts except for the googleTranslateElementInit() function in public/index.html:

  <div id="google_translate_element"></div>    
     
  <script     
    type="text/javascript"     
    src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"    
  >    
  </script> 

Then in src/App.vue or src/main.js methods section define the googleTranslateElementInit() function:

    googleTranslateElementInit() {
      window.google.translate.TranslateElement(
        { pageLanguage: "en" },
        "google_translate_element"
      );
    },

Note the extra window object needed.

Then call it when you're ready:

this.googleTranslateElementInit();

This long method is more flexible in that you have control on when to load the Google plugin and therefore run any other earlier code needed beforehand.

Had it all been put in index.html this would be difficult.

like image 124
kso Avatar answered Sep 05 '25 02:09

kso