2

In my web app I make use of Vue.js for a number of small components around the site. I store the Vue instances in their own js files which I concatonate, minify etc using gulp.

There is a small issue where if the target element for a particular Vue instance doesn't exist on the page a warning appears in the console:

[Vue warn]: Cannot find element: #vueElement

Although this doesn't harm anything as it is it left me wondering what the correct approach is to loading my Vue instances. Is there a way to prevent it firing if the target element isn't there?

harryg
  • 23,311
  • 45
  • 125
  • 198

3 Answers3

4
var element = document.getElementById('vueElement');

if(element != null)
{
    // your code will be here, an example is shown below
    var app = new Vue(
       el: '#vueElement'
    );
}

I Hope this works!

Anish Dcruz
  • 535
  • 2
  • 5
  • 8
2

I don't see any build-in way of doing this.

If you provide the el option in the constructor the Vue instance will automatically compile.

If you don't provide the eloption, you can manually compile the component using the $mount method.

So you can write something like this:

var app = new Vue({}); //don't include the el option here

if(document.getElementById("vueElement")) {
    app.$mount("#vueElement");      
} 
Needpoule
  • 4,476
  • 24
  • 33
1

Personally, for this purpose I use a function that will initialize Vue only if the target element exists:

function vueInit(elementId, options) {
    var element = document.getElementById(elementId);
    if (element) {
        options.el = element;
        new Vue(options);
    }
}

Usage:

vueInit("app", {
    data: {
        message: "It works!"
    }
});

https://jsfiddle.net/50wL7mdz/14194/

tocqueville
  • 5,270
  • 2
  • 40
  • 54
  • This way, you'll have to have jQuery or other query selector framework or library to deal with `$(selector)`, personally I'd suggest you to use the native / vanilla way (`document.getElementById`) as you won't need a whole library just to this purpose. =) Check @Needpoule's answer. – giovannipds Jun 01 '17 at 17:24
  • 1
    jQuery was not really the point of my answer... I removed it anyways. My point is to create a reusable function. You can use the selector you want inside it, it doesn't make a difference. – tocqueville Jun 02 '17 at 10:31
  • I still prefer @Needpoule's answer, though. – giovannipds Nov 09 '17 at 05:16