Why mounted hook fires even if el is not exists in Vue?

Viewed 957

I have a simple vue instance:

var vm = new Vue({
    el: "#myEl",
    data: {
        parent: null,
        posts: [],
        total: 0,
        currentPage: 0
    },
    mounted: function () {
        alert("mounted");
    }
});

Evething is fine, when #myEl is exist on the page, but if it not, mounter hook fires anyway.

But why? There is no element to mount instance for, so why it mounted anyway? What should I do in vue-way to check the el existence?

3 Answers

From Evan You

When el is not available, the component mounts in memory (similar to calling $mount() without arguments).

There are warnings in the console telling you that the target el cannot be found.

If you don't want this to happen, wrap the instance in a check for the element e.g.

if(document.querySelector('#el')){ ... }

According to the source code, if the element is not found then a warning is issued and a <div> is created instead.

It is your responsibility to check if the element exists or not (document.querySelector()) prior to instantiating the component.

The way I do it, though it may not be the vue-way, is just to query the element before trying to mount the instance. It would look something like:

const element = document.querySelector("#myEl");

if (element) {
  var vm = new Vue({
    el: element,
    ...
  });
}
Related