Я новичок в 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>
Ошибка в данных (): «Ошибка типа: невозможно прочитать свойство «длина» неопределенного» (Vue.js)!!! проблема связана с Math.floor(Math.random() * this.images.length) насколько я понимаю. В будущем я хочу использовать случайное изображение для генерации случайных изображений.
this.images не определено в тот момент, когда вы пытаетесь его использовать. Функция данных еще не завершена. Вы можете хранить изображения в переменной, а затем ссылаться на нее в операторе return.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.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]
};
}
};
this.images (или this.idx) еще не определено. Вы должны установить значение (например, null) на randomImage, а затем установить фактическое значение на крючке created:
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]
}
};
Как показывают другие ответы, 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]
};
}
};
Вместо этого вы можете использовать вычисляемое свойство для переменных данных, например:
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];
},
},
};
Также вы можете использовать переменные данных компонента только после создания или монтирования компонента.
Возможный дубликат Самоссылки в литералах/инициализаторах объектов