简体   繁体   中英

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.

Here is my 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

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? Why?
  3. It complains that the "this.$add is not a function"
  4. In the html the logs are never populated in the loop. why?
  1. Your ready should not be an object, it should be a function

2&3&4. Inside an anonymous function, this refers to something else. Use an arrow function to keep the scope of this , or store a reference to 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

You can also use mounted , something like:

mounted () {
    this.getLogs()    
}

Documentation .


data must be a function for a Vue component, but for a Vue instance it should be fine..

So for a Vue component, it should have data like following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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