Yes Man
Yes Man

Reputation: 341

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

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?

Upvotes: 3

Views: 1338

Answers (3)

Miguel Melón
Miguel Melón

Reputation: 21

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,
    ...
  });
}

Upvotes: 0

Decade Moon
Decade Moon

Reputation: 34286

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.

Upvotes: 1

Steven B.
Steven B.

Reputation: 9362

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')){ ... }

Upvotes: 2

Related Questions