Ошибка в data (): «Ошибка типа: невозможно прочитать свойство« длина »из неопределенного» (Vue.js) - PullRequest
0 голосов
/ 12 марта 2019

Я новичок в Vue.js, так что, возможно, я допустил глупую ошибку, но, честно говоря, не понимаю, почему у меня такая ошибка ... Можете ли вы помочь мне, пожалуйста?Вот код: Javascript:

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() {
    return {
      images: [
        bulma,
        bootstrap,
        css3,
        html5,
        illustrator,
        js,
        photoshop,
        vue,
        webpack
      ],
      idx: Math.floor(Math.random() * this.images.length),
      randomImage: this.images[this.idx]
    };
  }
};

и HTML:

  <div id="app">
    <div id="myContainer">
      <div id="nav">
        <router-link to="/">Home</router-link> |
        <router-link to="/about">About</router-link>
      </div>
      <router-view />
      <button v-on:click="animate">Test</button>
      <img v-for="image in images" :src="image" />
    </div>
  </div>

Ошибка в data (): «Ошибка типа: невозможно прочитать свойство« длина »из неопределенного» (Vue.js) !!!проблема связана с Math.floor (Math.random () * this.images.length) , как я понимаю.В будущем я хочу использовать randomPicture для генерации случайных картинок.

Ответы [ 4 ]

2 голосов
/ 12 марта 2019

Вы можете использовать вычисляемое свойство вместо переменных данных, таких как:

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];
    },
  },
};

Также вы можете использовать переменные данных компонента только после того, как компонент создан или смонтирован.

2 голосов
/ 12 марта 2019

Когда вы создаете свой компонент с этим:

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 (или this.idx) еще не определено.Вы должны установить значение (например, null) на randomImage, затем установить фактическое значение на 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]
  }
};
0 голосов
/ 12 марта 2019

Как и в других ответах, this.images еще не определено, когда вы его используете. Итак, попробуйте это:

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]
    };
  }
};
0 голосов
/ 12 марта 2019

Ваши данные пусты при монтировании компонента (потому что вы получаете его асинхронно), поэтому вам нужна дополнительная защита.

...