Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Injected event listeners in Vue JS project don't always fire on page change

I'm working with a Nuxt JS / Vue JS app with dynamic pages. My pages fetch data from a remote api which includes HTML and JS that needs to be executed.

In my context, I have a bunch of accordions, that when tapped should open the contents, so in the then block of my axios request I'm creating a script tag on the page with the contents:

const string = "some JS from api"
const injectTo = document.querySelector('[data-beam-injectes-interactivity]')
const script = document.createElement('script')
script.innerHTML = string
injectTo.appendChild(script)

The string of JS injected is:

function initDeviceGroupCollapses () {
  const buttons = document.querySelectorAll('[data-toggle="collapse"]')
  if (buttons) {
    for (const [index, button] of buttons.entries()) {
      if (button) {
        button.addEventListener('click', (event) => {
          event.stopPropagation()

          const target = event.target.dataset.target

          if (!target) {
            return
          }

          const collapse = document.querySelector(target)
          collapse.style.display = collapse.style.display == 'none' ? 'block' : 'none'
        }, false)
      }
    }
  }
}

The issue I'm having though is that if the JS is injected into a page where the HTML doesn't initially exist, the event listeners no longer fire on data-toggle="collapse".

How can I always make sure that the injected JS works?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda