0

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() {
  }
});

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Is that really the best way to accomplish this?
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.
@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?
Not aware of any - just a little more glue between components to setup and maintain.
0

You can push data in existing array by using JavaScript push method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

this.items.push(data)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.