0

i created a simple component but when i try to access data component it returns undefined here is my code:

Vue.component({
  template:`<div>{{message}}</div>`,
  data() {
     return { comments: [
        {title: 'hello' , message: 'world'},
        {title: 'hellowww' , message: 'worldssss'},
     ]}
  },
  mounted: function() {
      console.log(this.comments) // undefined. dosnt work
      console.log(this.$root.comments) //undefined. dosnt work
      console.log(comments) //undefined. dosnt work
  }

});

var app = new Vue({
   el: '#root'
});

1 Answers1

2

On of these may be due to the way you pasted in the question, but your code had some problems:

  • The Vue.component didn't declare its tag name.
    • Notice I added comments-component in Vue.component('comments-component', {.
  • The template of the component (template:`<div>{{message}}</div>`) declared a message variable that was not present.
    • I added message: "check the console", to data().

At this point, the mounted and this.comments in

mounted: function() {
    console.log(this.comments)
}

Work as expected.

See demo below.

Vue.component('comments-component', {
  template:`<div>{{message}}</div>`,
  data() {
     return { 
     message: "check the console",
     comments: [
        {title: 'hello' , message: 'world'},
        {title: 'hellowww' , message: 'worldssss'},
     ]}
  },
  mounted: function() {
      console.log(this.comments)
  }

});

var app = new Vue({
   el: '#root'
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>

<div id="root">
<comments-component></comments-component>
</div>
acdcjunior
  • 132,397
  • 37
  • 331
  • 304