0

I have a small vue.js component defined on a javascript.

Is any elegant way to instance the vue component only when the element is loaded?

The issue is I am receiving these warnings in other htmls where the element is not present:

vue.js:485 [Vue warn]: Cannot find element: #item

Because it's running this js everywhere

  new Vue({
    el: '#item',
  });

How is it taken care of in vue.js?

lapinkoira
  • 8,320
  • 9
  • 51
  • 94
  • Your problem could be solve with this previous post : https://stackoverflow.com/questions/29484431/vue-warn-cannot-find-element – Kyllian Vinkler Oct 02 '17 at 15:04
  • onload wont work on html pages which dont have the #item element – lapinkoira Oct 02 '17 at 15:05
  • Do you load your element with an ajax request ? I don't understand why it is not present on the first load – Kyllian Vinkler Oct 02 '17 at 15:09
  • Because you can have a index.html with a
    which wont give problems to Vue and then a stuff.html which wont have any
    and when javascript vue.js get executed in that page will complain because the #item element is not present in the page
    – lapinkoira Oct 02 '17 at 15:11
  • Can't you just load your script on the files with the #item element ? – Kyllian Vinkler Oct 02 '17 at 15:12
  • yeah... that's exactly what I am asking... and with elegant I mean a vue way to take care of that, not just a document.getElementById("#item"), imagine I have 100 vue components... – lapinkoira Oct 02 '17 at 15:13
  • Well I was talking about including your vue – Kyllian Vinkler Oct 02 '17 at 15:23

1 Answers1

1

Test for the element before creating the instance.

if(document.getElementById("#item")){
  new Vue({
    el: '#item',
  });
}
Mark
  • 90,562
  • 7
  • 108
  • 148
  • yeah I was thinking on this but it didnt look so elegant to me, is this then the only way to do this? – lapinkoira Oct 02 '17 at 15:04
  • I don't know of a vue-only way. However, this is only a warning, which means you shouldn't see it in production with debug mode off, if that's any conciliation. – Mark Oct 02 '17 at 15:05
  • 1
    ok, will leave this question open for a while and if nobody know a vue-only way I accept this answer – lapinkoira Oct 02 '17 at 15:08