我点击了一个按钮。我正在tbody
中创建HTML表行,因为我的thead
和body
处于不同的不同组件中,我正在使用ref
来获取tbody
组件的字段。
问题是我正在尝试将表格数据打印到打印机,并且单击时它没有采用其中的值。
码
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 = "";
}
}
在上面的代码中,由于未定义输入(因为refs没有给出值),因此会引发错误
这是我得到的错误:
Error in v-on handler: "TypeError: this.$refs.tablebody.getElementsByTagName is not a function"
这是my code sandbox。
主要问题是单击打印时,它正在打印空白行而不采用输入字段的值。还有其他更好的方法吗?
最佳答案
问题是v-for
,您不能在v-for中使用ref,因为它可能具有多个元素,然后Vue根本不确切知道您要引用的组件。
有两种解决方案。
第一种方法:更改模板。
从
<HelloWorld ref="tablebody" v-for="(row, key) in tableDatas" :key="key" v-bind.sync="row"></HelloWorld>
至
<div ref="tablebody">
<HelloWorld v-for="(row, key) in tableDatas" :key="key" v-bind.sync="row"></HelloWorld>
</div>
第二种方法:仅更改js。
我没有使用一个引用,而是使用了您想要的相同格式。
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 = "";
}
});
关于javascript - 动态输入字段未使用其值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59640143/