访问vue数据组件

时间:2018-02-23 11:10:45

标签: javascript vue.js vuejs2

我创建了一个简单的组件,但是当我尝试访问数据组件时,它返回undefined 这是我的代码:

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 个答案:

答案 0 :(得分:3)

关于这些可能是由于你粘贴在问题中的方式,但你的代码有一些问题:

  • Vue.component未声明其标记名称。
    • 注意我在comments-component中添加了Vue.component('comments-component', {
  • 组件的templatetemplate:`<div>{{message}}</div>`)声明了一个不存在的message变量。
    • 我将message: "check the console",添加到data()

此时,

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

按预期工作。

请参阅演示

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>