从Vue数据对象中的数组获取数组长度

时间:2020-04-04 00:29:54

标签: arrays vue.js

在vue中获取数组长度有点问题。数组 在数据对象中为

data() {
    return {
      slides: [
        {
          image: require("@/assets/img/carousel/couple.jpg"),
          caption:
            "A couple wearing masks kiss in a shopping area in downtown Shanghai, China, on February 16, 2020."
        },
        {
          image: require("@/assets/img/carousel/dogs.jpg"),
          caption:
            "Dogs wearing masks are seen in a shopping area in downtown Shanghai on February 16, 2020."
        },
         etc... ]

然后在方法中

methods: {
    playSlides() {
      this.imgSource = this.slides[this.currentSlide].image;
      this.figCaption = this.slides[this.currentSlide].caption;
      let slideInterval = setInterval(nextSlide, 2000);

      function nextSlide() {
        console.log(`slides.length is: ${this.slides.length}`);
        this.currentSlide = (this.currentSlide + 1) % this.slides.length; // % is same as mod operator
        console.log(Array.isArray(this.slides));
      }
    }
  }
};

我知道今天已经很漫长了,但是this.slides.length是不确定的?和Array.isArray(this.slides)为false。任何人都会看到最欣赏的问题是什么...

1 个答案:

答案 0 :(得分:1)

使用function name()时,this上下文不是父对象的this上下文,实际上是window的this上下文。

为了使this等于vue实例,您必须使用箭头函数,或使用.bind prototype显式绑定您希望this在函数中的内容

new Vue({
  data() {
    return {
      currentSlide: 1,
      slides: [{
          image: "@/assets/img/carousel/couple.jpg",
          caption: "A couple wearing masks kiss in a shopping area in downtown Shanghai, China, on February 16, 2020."
        },
        {
          image: "@/assets/img/carousel/dogs.jpg",
          caption: "Dogs wearing masks are seen in a shopping area in downtown Shanghai on February 16, 2020."
        }
      ]
    };
  },

  created() {
    this.playSlides();
    this.playSlides2();
  },

  methods: {
    playSlides() {
      this.imgSource = this.slides[this.currentSlide].image;
      this.figCaption = this.slides[this.currentSlide].caption;
      let slideInterval = setInterval(nextSlide.bind(this), 2000);

      function nextSlide() {
        console.log(`slides.length is: ${this.slides.length}`);
        this.currentSlide = (this.currentSlide + 1) % this.slides.length; // % is same as mod operator
        console.log(Array.isArray(this.slides));
      }
    },

    playSlides2() {
      this.imgSource = this.slides[this.currentSlide].image;
      this.figCaption = this.slides[this.currentSlide].caption;

      const nextSlide = () => {
        console.log(`slides.length is: ${this.slides.length}`);
        this.currentSlide = (this.currentSlide + 1) % this.slides.length; // % is same as mod operator
        console.log(Array.isArray(this.slides));
      }

      let slideInterval = setInterval(nextSlide, 2000);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>