Injecting Vue components and dynamically rendering them in real-time

Presently, I am in the process of developing a third-party application where Vue.js is being utilized to render components.

In this setup, the third-party app loads the component dynamically after the Vue app has been initialized and mounted. Due to this approach, I can only view the HTML structure of the component, not the actual template intended for rendering. Essentially, what I see when inspecting is something like

<my-component></my-component>
, without the content of the myComponent template.

An example illustrating this challenge can be found here: https://jsfiddle.net/EmeraldCodeNinja/31jkmzgc/12/. In this demo, clicking on a button appends a Vue component to the DOM using JavaScript.

I would appreciate suggestions on how to make this dynamic component rendering work effectively.

It's worth noting that the objective isn't to troubleshoot the JSFiddle example but rather to address the issue of dynamically rendering the added Vue component.

Provided below are the same HTML and JS snippets from the JSFiddle:

HTML

<script src="https://unpkg.com/vue@3.2.21/dist/vue.global.js"></script>
<div id="app">
  <sample-button></sample-button>
  <div id="new-button-wrap"></div>
</div>

<script id="sample-button" type="text/html">
    <button @click="addNew">Add Another Sample Button</button>
</script>

JS

const app = Vue.createApp();

app.component('sample-button', {
    template: '#sample-button',
  setup() {
    const addNew = function() {
      var div = document.createElement('div');
      var sampleBtn = document.createElement('sample-button');
      div.textContent = 'here a button should appear, but instead a tag is appearing';
      div.appendChild(sampleBtn);
        document.querySelector('#new-button-wrap').appendChild(div);
    }
    return {
        addNew
    }
  }
})

app.mount('#app');

Answer №1

To dynamically instantiate a Vue object, you can utilize the createApp and mount functions to attach it to the document object model.

createApp({
      template: "<button id=`my-button`>Click me!</button>",
}).mount(document.getElementById("button-container"));

Check out this CodeSandbox link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

Stopping the PanResponder in React Native temporarily: A guide

Here is the snippet to create an instance of the panResponder: constructor( props ) { super( props ); this.position = new Animated.ValueXY(); this.panResponder = PanResponder.create( { onStartShouldSetPanResponder: ( ) => true, ...

Navigating through an Angular 2 service

I'm struggling to retrieve an array from a JSON API and then loop through it. I can't seem to grasp how it all fits together. Any guidance would be greatly appreciated. This is what my service looks like: import {Injectable} from '@angular ...

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

Interactions with jQuery and the .load() method

Encountering a new issue with jQuery that I haven't seen before. Here's the code snippet: $(document).ready(function() { $('#browser_cat a').click( function() { $('#browser_cat').hide(); $('#browser_c ...

Why does Javascript Tic-Tac-Toe delay notifying the user until the entire board is full?

There have been a lot of questions about Tic-Tac-Toe javascript, but my issue is unique. My code works fine, but it doesn't declare a winner or a tie game until the entire board is filled. I suspect that my if statements are causing problems and can&a ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Displaying a meager 0.5% on the BootStrap progress indicator

Utilizing the bootstrap progress bar to display the percentage of a person's miles covered out of a total of 23,872 miles. Take user A as an example, they have covered only 5 miles: 5/23872 = 0.00020945 * 100 = 0.02094504 miles. Currently, anything ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Generate event listeners for buttons dynamically using a string without causing any conflicts

In my current project, I am using a for loop to dynamically populate an HTML table with values from an array. Each row in the table includes a button that needs to link to a different URL. thisbutton.addEventListener("click", function(){ window.l ...

The CSS navigation bar is not properly aligned in the center

This menu was constructed by me: JSBIN EDIT ; JSBIN DEMO Upon closer inspection, it appears that the menu is not centered in the middle of the bar; rather, it is centered higher up. My goal is to have it positioned lower, right in the middle. I ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Guide on getting a website name from a URL using Javascript

Is there a simple method to extract the site name from a URL string? For example: http://www.mysite.com/mypath/mypage -> www.mysite.com http://mysite.com/mypath/mypage -> mysite.com The JavaScript code runs on the mongodb CLI side, not within ...

Tips for stopping a file from being downloaded while printing using the print-html-element npm library?

Working on a desktop app using Electron Node.js, I have integrated the print-html-element library to print HTML pages. The printing process works fine, but after selecting the printer (Microsoft XPS Document Writer), it prompts me to download the output as ...

Arranging pre-selected checkboxes in MUI Datatable

I noticed that the checked data is appearing at the top of MUI data tables without any sorting. Checkbox In this image you can see that all the checked boxes are mixed up without any order. I would like to have all the checked rows displayed together and ...

How can I showcase a Google donut chart using an array of data in a React application?

I have created a doughnut chart that is supposed to take an array as data. However, when I input the array, nothing shows up on the chart. How can I create a chart with array data? sum.js ... const arr = []; arr.push({ key: capitalizeEachFirst ...

Unable to inject dependencies into Karma testing framework

I am facing the challenge of injecting the $urlRouterProvider into my tests, but I persistently encounter the unknown provider issue. My setup involves ui.router and the testing of directives, requiring access to these providers to prevent test failures... ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

The button must be programmed to remove a specific item from the server

I am currently developing an application to monitor my expenses using javascript, nodejs, express, and handlebars as the templating engine. Within the app, I have a "list" div that displays all of my expenses. (There is an add button next to the list, not ...