3

I'm trying to add two Vue.js instance to the same .js file as follows :

new Vue({
  el: '#step1',
  data: {
    value1: '',
  }
})


new Vue({
  el: '#step2',
  data: {
    value2: '',
  }
})

I call these two instances in two separate web pages. But I'm getting a Vue warning such as [Vue warn]: Cannot find element: #step1 not found or [Vue warn]: Cannot find element: #step2 not found. Am I doing it wrong? or is there any way that I can concatenate the two instances together?

1 Answer 1

5

If you must design your code this way, you could test if the element is on that page first before instantiating the Vue instance:

if( document.getElementById("step1") ) {
    new Vue({
      el: '#step1',
      data: {
        value1: '',
      }
    })
}

if( document.getElementById("step2") ) {
    new Vue({
      el: '#step2',
      data: {
        value2: '',
      }
})
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't solve anything. If in the page 2 there is a #step1 element, everything will break. You can't make sure that all the ids in a view are unique across all views.
If you are the one writing the code, then you can certainly come up with a naming convention that will be a unique/dynamic value based on the route or page id
In my case, the code already exists. We have lots of views with simple, short ids that make sense in the context of each view. We can't manage to refactor all of that. Even if it were possible, this solution becomes heavy if you have lots of views: for each view, you will perform getElementById N times, being N the number of total views you have.
I would not have included all of your vue js code in one file that loads on every page. I would dynamically load the js on each page that needs it.
Why not? That's the way big companies do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.