skip to Main Content

My API returns me the HTML. It has an option to switch between multiple languages and the content for all languages is already embedded in the single HTML.

There is an onload function inside the HTML that sets the default language.

function toggleLanguage(language) {
        // Hide all content
        document.querySelectorAll('[data-language]').forEach(function(el) {
            el.style.display = 'none';
        });

        // Show content for the selected language
        document.querySelectorAll('[data-language="' + language + '"]').forEach(function(el) {
            el.style.display = 'block';
        });
}

window.onload = function() {
    toggleLanguage('english');
};

<div class="abcd" data-language="english">Additional Charges & Terms</div>
<div class="abcd" data-language="spanish">Cargos y condiciones adicionales</div>

I’m using v-html inside my Vue file to render the content received from API

<div v-html="factsLabelTemplate"></div>

My issue here is window.onload is not getting triggered and I’m seeing the content in all languages.

2

Answers


  1. You are looking for the mounted lifecycle hook. Here is how you can use that:

    Your HTML:

    <div v-html="factsLabelTemplate"></div>
    

    Script:

    <script>
    import axios from 'axios';
    
    export default {
      data() {
        return {
          factsLabelTemplate: ''
        };
      },
      mounted() {
        axios.get('your-api-endpoint')
          .then(response => {
            this.factsLabelTemplate= response.data;
          })
          .catch(error => {
            console.error('Error fetching HTML content:', error);
          });
        
      }
    </script>
    
    Login or Signup to reply.
  2. you can make the call in nextTick api

    import { nextTick} from 'vue'
    // after api call
    factsLabelTemplate.value = response.data
    nextTick(()=>{
        toggleLanguage('english');
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search