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

VueJS开发DOB表单时filter()内`this`为undefined的解决方法

解决Vue中filter()方法里this为undefined的问题

嘿,这个问题我之前也碰到过,属于典型的函数this指向问题,咱们一步步来搞定它:

问题原因

当你在filter()的回调里用普通函数时,在Vue默认开启的严格模式环境下,这个回调函数的this并不会指向Vue实例,而是变成了undefined——这是因为普通函数会绑定自己的执行上下文,而filter默认不会把外层的this传递给回调函数。

三种解决方案

结合你的出生日期表单场景,这里有三个靠谱的解决办法:

1. 使用箭头函数(最推荐)

箭头函数不会创建自己的this,它会直接继承外层作用域的this(也就是你的Vue实例)。修改后的代码示例如下:

new Vue ({ 
  el: '.app', 
  data: { 
    months: [ 
      {month: 'January', days: 31}, 
      {month: 'February', days: 28}, 
      {month: 'March', days: 31}, 
      {month: 'April', days: 30}, 
      {month: 'May', days: 31}, 
      {month: 'June', days: 30}, 
      // 其他月份数据...
    ],
    selectedMonth: '' // 绑定用户选中的月份
  },
  methods: {
    getAvailableDays() {
      // 用箭头函数作为filter回调
      const targetMonth = this.months.filter(monthItem => {
        // 这里的this能正常指向Vue实例
        return monthItem.month === this.selectedMonth;
      });
      return targetMonth.length > 0 ? targetMonth[0].days : 0;
    }
  }
})

2. 提前保存this到变量

如果不想用箭头函数,可以在filter外面把Vue实例的this存到一个变量(比如vm)里,然后在回调里用这个变量访问实例属性:

methods: {
  getAvailableDays() {
    const vm = this; // 提前保存Vue实例的this
    const targetMonth = this.months.filter(function(monthItem) {
      // 用vm代替this访问Vue实例的属性
      return monthItem.month === vm.selectedMonth;
    });
    return targetMonth.length > 0 ? targetMonth[0].days : 0;
  }
}

3. 给filter()传递第二个参数指定this

filter()方法本身支持第二个参数,用来指定回调函数执行时的this指向,直接把Vue实例的this传进去就行:

methods: {
  getAvailableDays() {
    const targetMonth = this.months.filter(function(monthItem) {
      return monthItem.month === this.selectedMonth;
    }, this); // 这里的this就是Vue实例,作为回调的this指向
    return targetMonth.length > 0 ? targetMonth[0].days : 0;
  }
}

小提示

如果你的逻辑是写在计算属性里,上面的方法同样适用——计算属性里的this本来就指向Vue实例,只要解决filter回调的this指向问题就可以了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:59