Vue.js随机图像没有显示 [英] Vue.js random image not showing
问题描述
任何人都知道为什么这对我不起作用?我正在运行vue-cli构建。我没有收到任何错误,但图像没有显示。我是vue.js的新手,所以解决方案很可能非常简单。非常感谢任何帮助...
Anyone have an idea to why this isn't working for me? I'm running a vue-cli build. I don't get any errors, but the image isn't showing. I'm new to vue.js so the solution is most likely pretty simple. Any help is greatly appreciated...
<template>
<section>
<img :src="selectedImage" />
</section>
</template>
<script>
export default {
data: {
images: [
'http://via.placeholder.com/200x140',
'http://via.placeholder.com/200x100'
],
selectedImage: ''
},
created () {
const idx = Math.floor(Math.random() * this.images.length)
this.selectedImage = this.images[idx]
}
}
</script>
这是我的main.js文件:
This is my main.js file:
import Vue from 'vue'
import App from './App'
import router from './router'
import VueI18n from 'vue-i18n'
import messages from './components/locale'
Vue.config.productionTip = false
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en',
messages
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
i18n
})
推荐答案
这里 data
应该是一个返回对象的函数。
Here data
should be a function that returns an object.
<template>
<section>
<img :src="selectedImage" />
</section>
</template>
<script>
export default {
data () {
return {
images: [
'http://via.placeholder.com/200x140',
'http://via.placeholder.com/200x100'
],
selectedImage: ''
}
},
created () {
const idx = Math.floor(Math.random() * this.images.length)
this.selectedImage = this.images[idx]
}
}
</script>
以下是数据必须起作用的解释: https://vuejs.org/v2/guide/components.html#data-Must-Bea-a-功能
Here's an explanation why data must be function: https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
基本上,设计规定 data
必须是返回对象的函数,以避免交叉引用JavaScript对象。
Basically, it is dictated by design that data
must be a function that returns an object, to avoid cross referencing JavaScript objects.
这篇关于Vue.js随机图像没有显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!