Reputation: 12537
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?
Upvotes: 0
Views: 2087
Reputation: 846
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)
})
})
Upvotes: 0
Reputation: 11
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',
});
}
};
Upvotes: 1
Reputation: 1288
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 }
});
Upvotes: 1