[Vuejs]-Error in data(): "TypeError: Cannot read property 'length' of undefined" (Vue.js)

3πŸ‘

βœ…

When you create your component with this :

export default {
  name: "app",
  data() {
    return {
      images: [
        bulma,
        bootstrap,
        css3,
        html5,
        illustrator,
        js,
        photoshop,
        vue,
        webpack
      ],
      idx: Math.floor(Math.random() * this.images.length),
      randomImage: this.images[this.idx]
    };
  }
};

this.images (or this.idx) is not yet defined. You should set a value (like null) to randomImage, then set the actual value on the created hook :

export default {
  name: "app",
  data() {
    return {
      images: [
        bulma,
        bootstrap,
        css3,
        html5,
        illustrator,
        js,
        photoshop,
        vue,
        webpack
      ],
      idx: null,
      randomImage: null
    };
  },
  created() {
    this.idx = Math.floor(Math.random() * this.images.length)
    this.randomImage = this.images[this.idx]
  }
};
πŸ‘€Seblor

2πŸ‘

You can use a computed property instead to data variables like this:

export default {
  name: "app",
  data() {
    return {
      images: [
        bulma,
        bootstrap,
        css3,
        html5,
        illustrator,
        js,
        photoshop,
        vue,
        webpack
      ],
    };
  },
  computed: {
    idx() {
      return Math.floor(Math.random() * this.images.length);
    },
    randomImage() {
      return this.images[this.idx];
    },
  },
};

Also you can only use the component data variables once the component is created or mounted.

πŸ‘€Ronin Kr

0πŸ‘

Your data is empty when component is mounted (because you get it asynchronously), so you need an additional guard.

0πŸ‘

Like other answers indicate, this.images is not yet defined when you use it. So try this:

const bootstrap = require("./assets/bootstrap.png");
const bulma = require("./assets/bulma.png");
const css3 = require("./assets/css3.png");
const html5 = require("./assets/html5.png");
const illustrator = require("./assets/illustrator.png");
const js = require("./assets/js.png");
const photoshop = require("./assets/photoshop.png");
const vue = require("./assets/vue.png");
const webpack = require("./assets/webpack.png");

export default {
  name: "app",
  data() {
    const images = [
        bulma,
        bootstrap,
        css3,
        html5,
        illustrator,
        js,
        photoshop,
        vue,
        webpack
      ]
    const idx = Math.floor(Math.random() * images.length)
    return {
      images,
      idx,
      randomImage: images[idx]
    };
  }
};
πŸ‘€wang

Leave a comment