Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Hello everyone I'm getting a handle on Vue.js and I've created a component for a table (called setupTable). I want to be able to dynamically add data to this. I know that Vue.js listens to push on data elements but I can't seem to access the data element of my component through setupTableComponent.data. How would I access and append data to this component?

var setupTableComponent = Vue.extend({
  template: '<table id="data-table">'+
              '<tr v-for="item in items">'+
                '<td>{{item.b}}</td>' +
                '<td>{{item.d}}</td>' +
                '<td>{{item.t}}</td>' +
              '</tr>' +
            '</table>',
  data: function(){
    return { items: [
      { t: "Tester", b: "Buster", d: "Duster"},
      { t: "Not a Tester", b: "Not a Buster", d: "Not a Duster"}
    ]};
  }
});

Vue.component('setup-table-component', setupTableComponent);

var setUpDataTableV = new Vue({
  el: '#sidebar',
  ready: function() {
  }
});
share|improve this question

You could use the v-ref to access directly the child component:

<div id="sidebar">
  <button @click="onClick">Add item</button>
  <setup-table-component v-ref:table></setup-table-component>
</div>

Then, access the data of table ref like this:

this.$refs.table.$data.items.push(data)

https://jsfiddle.net/gjtf6sse/1/

share|improve this answer
    
Is that really the best way to accomplish this? – Chris Maness Feb 3 at 1:41
    
Two more options: 1) you could $broadcast an event on setUpDataTableV and catch it on setupTableComponent and 2) you could move items up to setUpDataTableV and pass a params reference to it down to setupTableComponent with two way binding. – David K. Hess Feb 3 at 2:45
    
@DavidK.Hess I really like the idea of passing a params reference in order to keep the two way data binding. Is there any downside to this approach? – Chris Maness Feb 3 at 14:55
    
Not aware of any - just a little more glue between components to setup and maintain. – David K. Hess Feb 3 at 15:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.