Vue文件如何获取当前实例?

对象里的函数如何用this获取当前实例?

export default {
  name:'calendar',
  data() {
    return {
      moment: moment(),
      month: monthArr[moment().month()],
      date: moment().date(),
      day: dayArr[moment().day()],
      swiperOption: {
        effect: 'flip',
        loop: true,
        onSlideNextEnd: function (swiper) {
          console.log('next');
          this.moment = this.moment.add(1, 'd');//这里的this不是实例的this
          this.month = monthArr[this.moment.month()];
          this.date = this.moment.date();
          this.day = dayArr[this.moment.day()];
        },
        onSlidePrevEnd: function (swiper) {
          console.log('prev;');
        }
      }
    }
  },
·
·
·
·
·
}
阅读 10.5k
3 个回答

1.首先你已经用了vue,那么你就应该上es6的写法,
2.你的data写的有问题,data里面放上了方法怎么能拿到this,你可以考虑换一个插件
3.如果你真要这么做的话:如下实现

export default {
  name:'calendar',
  data() {
    let _this = this
    return {
      moment: moment(),
      month: monthArr[moment().month()],
      date: moment().date(),
      day: dayArr[moment().day()],
      swiperOption: {
        effect: 'flip',
        loop: true,
        onSlideNextEnd(swiper) {
          console.log('next');
          _this.moment = _this.moment.add(1, 'd');//这里的this不是实例的this
          _this.month = monthArr[_this.moment.month()];
          _this.date = _this.moment.date();
          _this.day = dayArr[_this.moment.day()];
        },
        onSlidePrevEnd(swiper) {
          console.log('prev;');
        }
      }
    }
  },
}

此方法,我没事有不知道会不会造成递归错误,自己试验下理解下, 个人建议换一个组件

再写一个computed,把swiperOption 丢在 computed里 试下吧。这么写,实例还没创造出来,应该调用不到吧。

//直接用箭头函数就行了
data() {
    return {
      moment: moment(),
      month: monthArr[moment().month()],
      date: moment().date(),
      day: dayArr[moment().day()],
      swiperOption: {
        loop: true,
        onSlideNextStart: ()=> {
          this.moment = this.moment.add(1, 'd');
          this.month = monthArr[this.moment.month()];
          this.date = this.moment.date();
          this.day = dayArr[this.moment.day()];
        },
        onSlidePrevEnd: function (swiper) {
          console.log('prev;');
        }
      }
    }
  },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题