Skip to content
Advertisement

Vue js with simple JavaScript Vue is undefined

I am trying to understand how vue works. To do that I simplify it as much as possible, hence no webpack no CDNs or any other packages (unless its a necessity).

So, Came up with this but trying to inject a simple a variable into html gives vue is undefined error.

*vue.js file is taken from npm vue package.

<html>
<head>
  <script src="vue.js"></script>

  <script>
  new vue({
    data: 'This must be injected'
  }).$mount('#app');
  </script>

</head>
<body>
  <div id="app">
    <p> {{ data }} </p>
  </div>

  <h1>This is a sample header</h1>
</body>
</html>

Advertisement

Answer

You need to have Vue load after the Dom is ready so it can find the element to attach itself to — don’t put it in the head. Also it’s upper-case Vue. And Data can’t just be a naked property it should be a function that returns an object with your properties (it can also be an an object, but it’s not recommended once the app starts getting bigger).

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

  <p> {{ data }} </p>

</div>

<h1>This is a sample header</h1>
<script>
  Vue.config.productionTip = false
  new Vue({
    data(){ return {
      data: 'This must be injected'
    }
  }
  }).$mount('#app');
</script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement