[Vuejs]-Vue components on demand – [Vue warn]: Cannot find element

1👍

You can dynamically create an element with id my-app, before mount Vue.

import Vue from 'vue';

import Notification from "./components/Notification.vue";

var myAppElement = document.getElementById('my-app');

if (!myAppElement) {
   var newMyAppElement = document.createElement('div');
   newMyAppElement.setAttribute('id', 'my-app');
}

window.onload = function () {
    var main = new Vue({
    el: '#my-app',
    components: { Notification }
});

1👍

I solved by this way. I only instance Vue when #app it’s detected:

//only use Vue when #app detected
window.onload = function () {
    var app = document.getElementById('app');
    if (app) {
        const app = new Vue({
            el: '#app',
        });
    }
};

0👍

It’s simple create an element then mount the component to that element.

document.addEventListener('DOMContentLoaded', () => {
  const el = document.body.appendChild(document.createElement('notification'))
  const app = new Vue({
    el,
    render: h => h(Notification)
  })
})

Leave a comment