【发布时间】:2017-12-19 20:03:36
【问题描述】:
前言
我有一个允许用户添加行的表格,但用户要求将行添加到表格的顶部。
问题:** 使用推荐的拼接(添加到数组顶部)添加新行在 vue 1.x 中工作得很好,但在 vue 2.x 中添加第一个新行在添加第一个行时失败但添加 2 到 n 行效果很好 - 错误 **vue.min.js:6 TypeError: Cannot read property 'focus' of null 似乎告诉我新添加的行是 null 即使watch 在添加新行时触发。
如果我遗漏了某些内容,请联系我 - 下面的 vue 1.x 和 vue 2.x 都有一些问题可以正确地证明问题。
Vue.js 1.x
这在 vue.js v1.x 中运行良好。添加了新行,并且光标聚焦在 Date 列上:
小提琴:https://jsfiddle.net/barbedCoil/n2wrq39t/
这是添加新行的相关代码:
onAddTipEntry: function (employeeId, employeeJobCode)
{
HS.Main.vm.tipAddNew = true;
// find last row num
var last_row = 0;
_(this.tipEntries).forEach(function (entry)
{
if (entry.row_num > last_row) last_row = entry.row_num;
});
var newEntry = _.cloneDeep(HS.Main.vm.to_raw(HS.Main.vm.tipEntry));
newEntry.row_num = (last_row + 1);
newEntry.person_id = employeeId;
newEntry.job_code = employeeJobCode;
newEntry.tip_date = moment(this.businessDate).format("YYYY-MM-DD");
newEntry.status_code = this.status.new_code;
// we insert into the top of the array instead of bottom
this.tipEntries.splice(0, 0, newEntry);
}
以下是“手表”中的代码,它只是将焦点设置在日期字段上:
watch:
{
// we just watch to see when new entry by user
"tipEntries": function (val, oldVal)
{
if (this.tipAddNew === false) return;
// no error side effect even if fails
//$("#tip-0").focus();
// uncomment this to see the vue error
document.getElementById("tip-0").focus();
HS.Main.vm.tipAddNew = false;
},
},
Vue.js 2.x
在 vue.js 2.x 中,相同的代码 not 在添加的第一行上工作,但在后续行上工作正常。新行已添加,但光标不聚焦在 Date 列上(请参阅下面的“watch”sn-p 发生错误的位置)。 **我认为这不是真正的问题,而是副作用
这是控制台中显示的错误:
vue.min.js:6 TypeError: Cannot read property 'focus' of null at pt.tipEntries (test_vue2.js:72) at So.run (vue.min.js:7) at $e (vue.min.js:6) at Array.<anonymous> (vue.min.js:7) at e (vue.min.js:7) at <anonymous>
小提琴:https://jsfiddle.net/barbedCoil/4z6q8arn/2/
这是添加新行的相关代码。 这与 v1.x 代码完全相同:
onAddTipEntry: function (employeeId, employeeJobCode)
{
HS.Main.vm.tipAddNew = true;
// find last row num
var last_row = 0;
_(this.tipEntries).forEach(function (entry)
{
if (entry.row_num > last_row) last_row = entry.row_num;
});
var newEntry = _.cloneDeep(HS.Main.vm.to_raw(HS.Main.vm.tipEntry));
newEntry.row_num = (last_row + 1);
newEntry.person_id = employeeId;
newEntry.job_code = employeeJobCode;
newEntry.tip_date = moment(this.businessDate).format("YYYY-MM-DD");
newEntry.status_code = this.status.new_code;
// we insert into the top of the array instead of bottom
this.tipEntries.splice(0, 0, newEntry);
}
这是“手表”中的代码,它只是将焦点设置在日期字段上。 与 v1.x 相同的代码。请注意,错误来自以下焦点:
watch:
{
// we just watch to see when new entry by user
"tipEntries": function (val, oldVal)
{
if (this.tipAddNew === false) return;
// no error side effect even if fails
//$("#tip-0").focus();
// uncomment this to see the vue error
document.getElementById("tip-0").focus();
HS.Main.vm.tipAddNew = false;
},
},
【问题讨论】: