Reputation: 820
I have a button on click. I am creating HTML table rows in tbody
, as my thead
and body
are in different different components I am using ref
to get the fields of tbody
component.
The issue is I am trying to print my table data to printer and on click it is not taking the values inside that.
Code
print() {
const inputs = this.$refs.tablebody.getElementsByTagName("input"); // by this getting input fields
for (let input of inputs) {
input.placeholder = input.value;
}
this.$htmlToPaper("printMe");
for (let input of inputs) {
input.placeholder = "";
}
}
In the above it throws error as input is undefined as refs is not giving value
This is the error I am getting:
Error in v-on handler: "TypeError: this.$refs.tablebody.getElementsByTagName is not a function"
Here is my code sandbox.
The main issue is on click of print it is printing blank rows not taking values of input fields. Is there any other approach which is better?
Upvotes: 0
Views: 191
Reputation: 1402
The problem is v-for
, you cannot use ref in v-for, as it may have multiple elements, then Vue simply do not know exactly which component you are referring.
There are two solutions to solve it.
First Approach: change template.
from
<HelloWorld ref="tablebody" v-for="(row, key) in tableDatas" :key="key" v-bind.sync="row"></HelloWorld>
to
<div ref="tablebody">
<HelloWorld v-for="(row, key) in tableDatas" :key="key" v-bind.sync="row"></HelloWorld>
</div>
Second Approach: change js only.
Instead of using one ref, I use the same format as you would like.
const tableBodies = this.$refs.tablebody;
tableBodies.forEach(tablebody => {
const inputs = tablebody.$el.getElementsByTagName("input");
for (let input of inputs) {
input.placeholder = input.value;
}
this.$htmlToPaper("printMe");
for (let input of inputs) {
input.placeholder = "";
}
});
Upvotes: 2