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

210
Vistas
Vue 3: How to add component programmatically?

I know there are a bunch of questions similar to this, but from what I've seen they don't seem to work. I come from a react background and am exploring Vue now, so apologies if my expectations are incorrect.

My example can be simply defined like:

<template>
  <div class="test" @click="passedFunction">Click me</div>
</template>
<script>
export default {
  name: 'TestComponent',
  props: {
    passedFunction: {
      type: Function,
      default: () => {},
    }
  }
}
</script>
<style scoped>
.test { background-color: blue; }
</style>

I would like to be able to just do:

import TestComponent from 'TestComponent.vue';
...
methods: {
  testComponentHandler: function() {
    console.log('It worked!');
  },
  addComponent: function() {
    const targetContainer = document.getElementById('target-div');
    const newComponent = new TestComponent({
      passedFunction: this.testComponentHandler
    });
    targetContainer.appendChild(newComponent);
  },
}

I was almost able to get it working like this:

const testComponentElement = defineCustomElement(TestComponent);
        customElements.define('test-component', testComponentElement);
        const newTestComponent = new testComponentElement({
          passedFunction: this.testComponentHandler,
        });
target.appendNode(newTestComponent);

This adds the element, but it's within a tag (as defined by the new customElements) and is within a '#shadow-root' which seems to mean that the component CSS doesn't work at all. Additionally, I am unable to access any elements from within the shadow-root and I'm not able to access elements within the shadow-root from outside of it, it's as though just the outer-element exists.

I feel like I'm missing something... any input?

Edit: Added part about not being able to access in/out of shadow-root.

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