Compiling Vue components upon insertion into the DOM

Is there a way to dynamically insert a compiled element into the DOM, without having a pre-defined location as instructed in the documentation?

var res = Vue.compile('<div><span>{{ msg }}</span></div>')
new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
})

The usual approaches using v-for or v-if/show won't work either since they require predefined elements.

I attempted something like this...

document.getElementById('elPai').insertAdjacentHTML('beforeend', Vue.compile('<div><span>{{ msg }}</span></div>'));

It returns an object containing 'render' and 'StaticRenderFns', but I couldn't find the compiled result in these objects. It seems like it is stored in a 'Promise' that only gets triggered when the element is already defined in the 'DOM'.

So, how can we insert compiled elements into DOM using 'Vue 2'?

Answer №1

Give this a shot

let MyVueComponent = Vue.extend({
  template: '<div>Greetings!</div>'
})

new MyVueComponent().$mount('#root')

Check out more details at: https://v2.vuejs.org/v2/api/#vm-mount

Answer №2

Great effort! You are very close to the correct solution, just remember when mounting it, utilize .$mount() (similar to @Wszerad's response):

console.clear();

var result = Vue.compile('<div><span>{{ msg }}</span></div>');

console.log(result);

var vm = new Vue({
  data: {
    msg: 'hello'
  },
  render: result.render,
  staticRenderFns: result.staticRenderFns
});

vm.$mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e686b7b5e2c302b302b">[email protected]</a>/dist/vue.js"></script>
<body>
  <div id="app"></div>
</body>

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

What could be causing Jquery to not function properly in an Angular controller?

Can someone please help me understand why my code is not working in JSFiddle? Any assistance would be appreciated! UPDATE: I have to admit, the negative feedback is disheartening. I may not know everything, but asking questions is how we learn. What' ...

The Safari keyboard navigation feature suddenly disappeared after uploading to Google App Engine

My current website is built using Vue.js (2.x) and deployed on Google App Engine. After testing the deployed application in Safari, I noticed that the accessibility feature "'skip navigation' on :focus" was no longer functioning proper ...

After logging in, the initial API request is unauthorized and requires a page refresh for access (Using Laravel Sanctum and VueJS)

I've been grappling with this 401 issue for quite some time now. Even after successfully logging in and obtaining the token, I continue to encounter a 401 exception on the initial page load. Strangely, the error disappears upon refreshing the page. It ...

Combine arrays into a single array

If I have an array that contains arrays within it, my goal is to flatten it and create a single array with all the values. let arrWithArrs = [[1,2,3], [4,5,6]]; let array = arrWithArrs.map(arr => ...arr); The current approach does not yield the desire ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

utilize javascript to style iframe from an external domain without access to its DOM structure

I have two websites, example.com and example1.com. I'm trying to display the content of example1.com within an iframe on example.com. For instance: Add this code to example.com: <iframe src='http://example1.com'> Then add the follow ...

What is the best way to resize an iframe containing a video to match the size of its parent

When using CSS, it is possible to stretch and adjust the ratio of an image to fully cover its parent div. The image will also resize accordingly if the parent div is responsive. Is this same effect achievable with videos (iframe) as well? EDIT: I am conce ...

Optimize your website by caching static pages and content using Node.js

When it comes to caching static content using nodejs, there seem to be two main methods that can be utilized: The first method involves using nodejs and utilizing the following code: app.use(express.static(path.join(__dirname, 'public'), { max ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Creating Shortened Links with Bit.ly API Solely Using Javascript

Lately, I have been experimenting with Javascript. I was trying to shorten some URLs using bit.ly for tweeting purposes when an idea struck me: why not create an automated process that utilises their API to shrink any URLs I need? However, upon checking ...

Tailwind CSS styling appears to be malfunctioning in the production build of Next.js, despite functioning correctly in the

Despite following the proper build process with npm run build + npm run start, my Tailwind styling is not functioning correctly in the production build. Oddly enough, when I use npm run dev, the styling works as expected and my page displays with a purple ...

PHP not compatible with Fancybox iframe

I'm facing a simple problem that I can't seem to figure out. I have a button that, when clicked, opens a fancybox with an iframe displaying a page from my website. This page includes a form for sending an email. Everything works fine except that ...

PHP scripts for performing multiplication and subtraction operations

My goal is to create a PHP script that can determine the total miles driven by a car rental customer (at a rate of 0.12 cents per mile), calculate the cost based on the number of days they rented the car ($15 per day), and display the grand total in a text ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

The challenge of Cross-Origin Resource Sharing with AjaxSubmit compared to a traditional Ajax request

My dilemma involves two applications interacting on Google's App Engine, each operating within its own domain. To enable communication between them, I have successfully implemented CORS in Python using the following code: self.response.headers.add_he ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Having difficulty in sending SMS through smsgateway.me following the recent update

Today, I encountered an issue while trying to send SMS messages programmatically using PHP from localhost. The problem arose after updating to version 4 of smsgateway.me and I am unable to send any messages. I am struggling to figure out how to pass the AP ...

Emphasize a checkbox by selecting it when another checkbox is checked

I have a question about checkboxes and highlighting the checkmarks. The issue I am facing is that I have multiple checkboxes with the same ID for different screen resolutions. When I click on the label for "Check 1" it highlights the corresponding checkmar ...

VueJS encountered an issue while displaying the image

I am facing an issue with VueJS while trying to populate my index.html with images fetched from the iTunes API. The API returns a URL to an image, but I am struggling to render them on my webpage. The 'item' variable holds the object data. Initi ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...