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'
});
5
  • 1
    Is that missing : after comments unintentional or intentional? Commented Feb 23, 2018 at 11:12
  • Or the closing </div>. Commented Feb 23, 2018 at 11:13
  • yeah sorry i typed codes again , didnt copy so that happen ill edit it now Commented Feb 23, 2018 at 11:13
  • Possible duplicate of VueJS: why is "this" undefined? Commented Feb 23, 2018 at 11:20
  • i tried mounted () { //codes } , same results Commented Feb 23, 2018 at 11:23

1 Answer 1

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/[email protected]/dist/vue.min.js"></script>

<div id="root">
<comments-component></comments-component>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.