Vue.js random image not showing

前端 未结 1 720
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 18:19

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

相关标签:
1条回答
  • 2021-01-25 18:37

    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>
    

    Here's an explanation why data must be function: https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

    Basically, it is dictated by design that data must be a function that returns an object, to avoid cross referencing JavaScript objects.

    0 讨论(0)
提交回复
热议问题