Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!