使用 Vue.js 设置数据

setting data with Vue.js

抱歉我的初学者问题,但从昨天开始我就被困在一个基本问题上,我无法找到解决方案。

我想用一些 json 对象填充我的变量日志并将其呈现在数组中。

这是我的 html :

<tbody>

  <tr v-for="log in logs">
    <td>{{log.incident}}</td>
    <td>{{log.request}}</td>
    <td>{{log.requested}}</td>
    <td>{{log.message}}</td>               
  </tr>            

</tbody>

这是我的 JS

let vm = new Vue({
    el: '#container',
    components: {
        'table-header': tableHeader,
    },
    data: {
        logs: []
    },
    methods: {
        getLogs() {
            addon.port.on('log', function (data) {
               console.log(data);
               this.$add('logs',data)
            });
        }
    },
    ready:{
        function(){this.getLogs()}
    }

});

vm.getLogs();
  1. 准备似乎不起作用。为什么?
  2. this.logs未定义?为什么?
  3. 它抱怨 "this.$add is not a function"
  4. 在 html 中,日志永远不会在循环中填充。为什么?

我不知道你的例子是否有效,我现在无法测试它,但我已经习惯了这样的语法:

ready: function(){
    console.log('ready);
}

你的方法也一样。也许检查文档并应用开始时给出的语法。

https://vuejs.org/guide/index.html#Getting-Started

您也可以使用 mounted,例如:

mounted () {
    this.getLogs()    
}

Documentation.


data must be a function 对于 Vue 组件,但对于 Vue 实例应该没问题..

所以对于一个 Vue 组件,它应该有如下数据:

data: function () {
  return {
    logs : []
  }
}
  1. 你的 ready 不应该是一个对象,它应该是一个函数

2&3&4。在匿名函数内部,this 指的是其他东西。使用箭头函数来保持 this 的范围,或者存储对 this

的引用

let vm = new Vue({
     el: '#container',
     components: {
         'table-header': tableHeader,
     },
     data: {
         logs: []
     },
     methods: {
         getLogs() {
             addon.port.on('log', (data) => {
                console.log(data);
                this.$add('logs',data)
             });
         }
     },
     ready() {
         this.getLogs()
     }

     });

//OR do this
getLogs() {
  var that = this;
             addon.port.on('log', function(data) {
                console.log(data);
                that.$add('logs',data)
             });
         }