Hamayun Khan
Hamayun Khan

Reputation: 23

Vue component not displaying data in HTML page

index.html:

<body>
    <div id="app">
        {{ message }}
    </div>

    <div id="counter">
        {{ counter }}
    </div>
      
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript" src="index.js"></script>
</body>

index.js:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
})

const Counter = {
    data() {
        return {
            counter: 0
        }
    }
}
  
Vue.createApp(Counter).mount('#counter')

and the output is:

Hello Vue!
{{ counter }}

Why is my code for counter not working?

Upvotes: 0

Views: 334

Answers (1)

Dan Knights
Dan Knights

Reputation: 8378

You're using the syntax for two separate versions of Vue.

new Vue is v2, Vue.createApp is v3.

For your code to work with v2:

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

const Counter = new Vue({
  el: '#counter',
  data() {
    return {
      counter: 0
    }
  }
})
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">
  {{ message }}
</div>

<div id="counter">
  {{ counter }}
</div>


For your code to work with v3:

var app = Vue.createApp({
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
})

const Counter = Vue.createApp({
  data() {
    return {
      counter: 0
    }
  }
})

app.mount('#app');
Counter.mount('#counter');
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  {{ message }}
</div>

<div id="counter">
  {{ counter }}
</div>

Upvotes: 1

Related Questions