简体   繁体   English

用Vue.js设置数据

[英]setting data with Vue.js

Sorry for my begginner question, but I'm stucked since yesterday on a basic problem which i cannot figure out the solution. 对不起我的初学者问题,但是自昨天以来,我一直陷在一个基本问题上,我无法找出解决方案。

I want to fill my variable logs with some json object and render it in an array. 我想用一些json对象填充变量日志,并将其呈现在数组中。

Here is my html : 这是我的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>

and here is my JS 这是我的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. The ready does not seems to work. 准备好似乎没有用。 Why? 为什么?
  2. The this.logs is undefined? this.logs是未定义的吗? Why? 为什么?
  3. It complains that the "this.$add is not a function" 它抱怨“ this。$ add不是函数”
  4. In the html the logs are never populated in the loop. 在html中,日志永远不会填充到循环中。 why? 为什么?
  1. Your ready should not be an object, it should be a function 您准备好的不应该是对象,而应该是一个功能

2&3&4. 2&3&4。 Inside an anonymous function, this refers to something else. 在匿名函数内部, this引用了其他内容。 Use an arrow function to keep the scope of this , or store a reference to 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) }); } 

I don't know if your example is valid and I can't test it at the moment but I am used to the syntax like so: 我不知道您的示例是否有效,目前无法测试,但我已经习惯了这样的语法:

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

Same goes for your methods. 您的方法也是如此。 Maybe check the documentation and apply the syntax like given there to begin with. 也许检查文档并应用此处给出的语法开始。

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

You can also use mounted , something like: 您还可以使用mounted ,例如:

mounted () {
    this.getLogs()    
}

Documentation . 文件资料


data must be a function for a Vue component, but for a Vue instance it should be fine.. 数据必须是 Vue组件的函数 ,但对于Vue实例应该没问题。

So for a Vue component, it should have data like following: 因此,对于Vue组件,它应具有如下数据:

data: function () {
  return {
    logs : []
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM