Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda