访问VUE数据组件



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

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'
});

可能是由于您在问题中粘贴的方式,但是您的代码遇到了一些问题:

  • Vue.component没有声明其标签名称。
    • 注意我在Vue.component('comments-component', {中添加了comments-component
  • 组件(template:`<div>{{message}}</div>`(的template声明了不存在的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>

最新更新