You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue深度监听date对象属性触发ESLint func-names告警如何修复

修复ESLint func-names告警方案

这个告警是ESLint的func-names规则触发的,该规则要求所有函数表达式必须填写函数名,你当前写的watch回调都是匿名函数表达式,所以触发了告警。下面是几种可行的修复方案:


方案1:给匿名函数加上函数名

直接给每个watch的回调函数定义语义化的名称即可,符合func-names规则要求:

watch: {
  "date.fontColor": function updateFontColor(val) {
    this.date.fontColor = val;
    this.$store.commit("setDate", this.date);
  },
  "date.datePosition": function updateDatePosition(val) {
    this.date.datePosition = val;
    this.$store.commit("setDate", this.date);
  },
  "date.backgroundColor": function updateBackgroundColor(val) {
    this.date.backgroundColor = val;
    this.$store.commit("setDate", this.date);
  },
  "date.fontsize": function updateFontsize(val) {
    this.date.fontsize = val;
    this.$store.commit("setDate", this.date);
  },
}

方案2:改用箭头函数

func-names规则不会校验箭头函数,直接改写为箭头函数也能消除告警,Vue的watch回调场景下箭头函数的this指向组件实例,符合使用要求:

watch: {
  "date.fontColor": (val) => {
    this.date.fontColor = val;
    this.$store.commit("setDate", this.date);
  },
  "date.datePosition": (val) => {
    this.date.datePosition = val;
    this.$store.commit("setDate", this.date);
  },
  "date.backgroundColor": (val) => {
    this.date.backgroundColor = val;
    this.$store.commit("setDate", this.date);
  },
  "date.fontsize": (val) => {
    this.date.fontsize = val;
    this.$store.commit("setDate", this.date);
  },
}

方案3:优化重复逻辑,减少冗余代码

你当前所有watch回调的逻辑高度一致,可以抽离公共方法或者直接开启深度监听,既消除告警又简化代码:

抽离公共处理方法

methods: {
  updateDateProp(val, propName) {
    this.date[propName] = val;
    this.$store.commit("setDate", this.date);
  }
},
watch: {
  "date.fontColor": function handleFontColorChange(val) {
    this.updateDateProp(val, 'fontColor')
  },
  "date.datePosition": function handlePositionChange(val) {
    this.updateDateProp(val, 'datePosition')
  },
  "date.backgroundColor": function handleBgColorChange(val) {
    this.updateDateProp(val, 'backgroundColor')
  },
  "date.fontsize": function handleFontsizeChange(val) {
    this.updateDateProp(val, 'fontsize')
  },
}

直接深度监听整个date对象

不需要单独监听每个子属性,代码更简洁:

watch: {
  date: {
    deep: true,
    handler: function updateDate(val) {
      this.$store.commit("setDate", val);
    }
  }
}

方案4:临时忽略该规则(不推荐)

如果只是想临时消除告警不想改代码,可以在告警的代码行上方加注释忽略func-names规则:

watch: {
  // eslint-disable-next-line func-names
  "date.fontsize": function (val) {
    this.date.fontsize = val;
    this.$store.commit("setDate", this.date);
  },
}

内容的提问来源于stack exchange,提问作者haha861924

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 00:45:11