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

207
Visualizações
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 à 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