0

I am working on a php/laravel project that requires using some vue components in some areas. Currently, my vue component looks as follows:

import Vue from 'vue';

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

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

However, on pages where I do not have a #my-app element I am getting the following error:

[Vue warn]: Cannot find element: #my-app 

Is there a way to prevent this warning? Another way to ask this is, is there way to use my notification component on pages where I need it by creating a #my-app element and not have a #my-app element altogether on pages were I do not need it?

Or if I understand this correctly, I need a root #my-app element regardless of if I'm using the Notification component?

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231

3 Answers3

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 }
});
Eyal Cohen
  • 1,188
  • 2
  • 15
  • 27
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)
  })
})
Son Tr.
  • 776
  • 6
  • 18