vue数据更新了,但视图不刷新的诡异问题 this.$set

张开发
2026/4/10 4:35:39 15 分钟阅读

分享文章

vue数据更新了,但视图不刷新的诡异问题 this.$set
在 Vue 2 开发中我们经常会遇到数据更新了但视图不刷新的诡异问题。尤其在你这份保养规则配置的业务代码中批量填充首次保养时间、单个选择日期时强制刷新$forceUpdate无效、视图不更新核心原因就是Vue 2 无法检测对象新增 / 未监听属性的变更唯一的标准解决方案就是使用this.$sethandleRuleConfirm(selectedRules) { //每次保存时存储原始数据并去重 this.selectedRules selectedRules; // 按 locationId 合并数据 const groupedData selectedRules.reduce((acc, item) { // 添加 stateName 字段 item.stateName item.state 1 ? 正常 : 停用; // 添加 isCss 字段 item.isCss false; //默认当天 this.$set( item, planTime, this.$utils.dateFormat(yyyy-MM-dd 00:00:00, new Date()) ); const locationId item.locationId; if (!acc[locationId]) { acc[locationId] { locationName: item.locationName, locationLabel: item.locationLabel, locationId: item.locationId, locationCode: item.locationCode, data: [], }; } acc[locationId].data.push(item); return acc; }, {}); // 转换为数组 this.listData Object.values(groupedData); // 设置所有折叠面板默认展开 this.activeNames this.listData.map((_, index) index.toString()); console.log(this.activeNames, this.activeNames); this.$message.success(已选择 ${selectedRules.length} 条保养规则); },初次给对象新增添加字段时使用this.$set( item, planTime, this.$utils.dateFormat(yyyy-MM-dd 00:00:00, new Date()) );

更多文章