Carol.Kar
Carol.Kar

Reputation: 5345

VueJS Component does not load

I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code:

Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
  data: {
    msg: 'hello'
  }
});

new Vue({
  el: '#app-6'
});
<!DOCTYPE html>
<html lang="en">
<meta>
<meta charset="UTF-8">
<title>Components in Vue.js</title>
</meta>

<body>

  <div id="app-6">
    test
    <my-component></my-component>
  </div>

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

</html>

Any suggestions what I am doing wrong?

I appreciate your replies!

Upvotes: 2

Views: 2078

Answers (3)

Imre_G
Imre_G

Reputation: 2535

Your data should be a function like this:

data () {
    return {
        msg: 'Hello'
    }
}

More information here: https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

Upvotes: 2

Zaking
Zaking

Reputation: 11

you should do it like this.

Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
   data: function () {
    return {
      msg: 'Hello'
   }
}
});

Upvotes: 1

Viplock
Viplock

Reputation: 3319

Data Must be a function always

var data={msg: 'hello'}    
Vue.component('my-component', {
  template: '<div>{{ msg }}</div>',
  data:function() {
       return data;
  }
});

new Vue({
  el: '#app-6'
});
<!DOCTYPE html>
<html lang="en">
<meta>
<meta charset="UTF-8">
<title>Components in Vue.js</title>
</meta>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script>
  <div id="app-6">
    test
    <my-component></my-component>
  </div>


</body>

</html>

Upvotes: 4

Related Questions