2017-12-29 37 views
1

誰かが私のためにうまくいかない理由を知っていますか?私はvue-cliビルドを実行しています。私はエラーは出ませんが、イメージは表示されません。私はvue.jsの新機能ですので、ソリューションはかなりシンプルです。すべてのヘルプは大歓迎です...Vue.jsランダムイメージが表示されない

<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ファイルである:ここで

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 
}) 

答えて

2

dataは、オブジェクトを返す関数でなければなりません。 https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

基本的に、それはdataは、JavaScriptのオブジェクトを相互参照を避けるために、オブジェクトを返す関数でなければならない設計によって決定されます。データは関数でなければならない理由

<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> 

は、ここでの説明です。

+0

なぜこの場合、関数にする必要がありますか? – Ward

+2

こちらをご覧ください:https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function。編集を追加しました。 – Manish

+0

ありがとうございます@Manish –

関連する問題