18

I'm building an app that a page has some vms, in others not. When we change from one page to another show the following warning:

[Vue warn]: Cannot find element: #element-id

How do I instantiate VMs only if there is the element on the page and avoid the error?

NOTE: I'm using Rails asset pipeline, so, all the javascript is concatenated into a single file.

Alexandre Magro
  • 1,131
  • 2
  • 10
  • 22

2 Answers2

44

There are no issues just leaving it as is. This is just a warning that only runs when debug mode is on, so you should have it turned off in production anyway.

If you want to get rid of it, just check if the element exists before launching Vue -

if(document.getElementById("element-id")){
  new Vue({...})
}

Ref: How to check if element exists in the visible DOM?

Community
  • 1
  • 1
Jeff
  • 24,623
  • 4
  • 69
  • 78
  • Excellent answer, i just came to this situation of having libraries preloaded and thought this would be an issue. – Kiko Seijo Jul 30 '17 at 20:12
3

This is a bit of an old question. I found this Vue example being useful

https://v2.vuejs.org/v2/api/#Vue-extend

So you can create a Vue class and initiate it only if the dom element is present in the DOM.

// create constructor
var Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
  data: function () {
    return {
      firstName: 'Walter',
      lastName: 'White',
      alias: 'Heisenberg'
    }
  }
})
// create an instance of Profile and mount it on an element
if(document.getElementById("element-id")){
  new Profile().$mount('#element-id')
}
tony19
  • 125,647
  • 18
  • 229
  • 307
nivanka
  • 1,352
  • 6
  • 23
  • 36